简体   繁体   English

用边界创建正则表达式

[英]Creating a Regular Expression with boundery

I want to create a Regex in c#,I write the following code: 我想在c#中创建一个正则表达式,我编写以下代码:

        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. 我的目标只有“愉快”和“快乐”才能找到,所以我写“\\ b”来限制正则表达式。 but when the app runs always x eqquals zero, and when "\\b" is dropped, x equals three. 但是当应用程序运行时,x eqquals为零,当“\\ b”被删除时,x等于3。

Does anyone know why? 有谁知道为什么? Thanks Rachel 谢谢雷切尔

\\G never matches here I think. \\G我想这里从来没有匹配。 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. 如果省略\\b ,则表达式匹配“ happ”的三倍;如果使用\\b ,则“ happ”不能匹配,因此计数为零。

Use something like 使用类似的东西

@"happ(iness|ily)\b"

as Kobi suggestes in his comment. 正如Kobi在他的评论中建议的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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