Rachel
Rachel

Reputation: 15

Creating a Regular Expression with boundery

I want to create a Regex in c#,I write the following code:

        string temp = "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

Upvotes: 0

Views: 73

Answers (1)

MartinStettner
MartinStettner

Reputation: 29174

\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.

Upvotes: 2

Related Questions