简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM