0

假设单词“ABC”是关键字,

并且正则表达式模式是

[^a-z^A-Z]ABC[^a-z^A-Z]

我希望以下输入返回 true:

 hello how are you ABC hello how are you
 hello how are you.ABC0hello how are you

以下输入返回false:

"hello how are youABChello how are you"

问题是,如果“ABC”出现在字符串的开头或结尾,则正则表达式不会拾取它。如果我不写 [^az^AZ] 而写 [^az^AZ]* 那么我不想要的字符串也会被选中。

编写这个正则表达式的正确方法是什么?

4

1 回答 1

2

使用negative lookbehindlookahead断言:

var pattern = new Regex("(?<![a-zA-z])ABC(?![a-zA-z])");

请参阅:http: //msdn.microsoft.com/en-us/library/az24scfc.aspx#grouping_constructs

于 2012-11-11T03:47:10.450 回答