Creating a Regular Expression with boundery
I want to create a Regex in c#,I write the following code:
string temp =开发者_Python百科 "happ";
Regex reg = new Regex(temp + @"((\G(iness))|(\G(ily))*)\b");
string str = "happily happiness happy";
int x = reg.Matches(str).Count;
My target that only "happily" and "happiness" will be found, so I write "\b", to limit the regex. but when the app runs always x eqquals zero, and when "\b" is dropped, x equals three.
Does anyone know why? Thanks Rachel
\G
never matches here I think. It makes only sense at the beginning of an expression, since it says that the expression should directly follow the previous match.
If you omit \b
, your expression matches three times "happ", if you use \b
, "happ" cannot be matched and therefore the count is zero.
Use something like
@"happ(iness|ily)\b"
as Kobi suggestes in his comment.
精彩评论