使用正则表达式匹配除特定数字外的任意数字。

3

使用正则表达式,我想匹配以下字符串:

  • 3.2 标题1
  • 3.5 标题2
  • 3.10 标题3

我尝试了 @"^3\.\d+[ ]." ,但是我不想匹配以单个“1”结尾的字符串,例如:

  • 3.1 标题4

我尝试了 @"^3\.[^1][ ]." ,但它无法匹配像 3.10 这样的字符串。

那么,如何匹配除数字“1”之外的任何数字呢?

谢谢您提前的帮助。

1个回答

6
使用正向前瞻断言和单词边界锚点来匹配:

请参考 正向前瞻断言 ,以及单词边界锚点

@"^3\.(?!1\b)\d+ ."

解释:

^   # Start of the string
3\. # Match 3.
(?! # Assert that it's impossible to match...
 1  # the digit 1 
 \b # followed by a word boundary (i. e. assert that the number ends here)
)   # End of lookahead assertion
\d+ # Then match any number.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接