匹配包含数字和下划线的整个单词不在引号之间

时间:2015-06-19 10:17:03

标签: c# regex

我正在努力寻找获得此正则表达式的正确方法:

\b([A-Za-z]|_)+\b

不匹配引号('AND“)之间的整个单词,所以:

example_ _where // matches: example_, _where
this would "not be matched" // matches: this and would
while this would // matches: while this would
while 'this' would // matches: while and would

此外,我试图找出如何包含包含数字的单词,但不仅包括数字,所以再次:

this is number 0 // matches: this, is and number
numb3r f1ve // matches: numb3r and f1ve
example_ _where // matches: example_ and _where
this would "not be 9 matched" // matches: this and would
while 'this' would // matches: while and would

目标是尝试仅匹配在大多数常见编程语言中有效变量名称的单词,而不匹配字符串中的任何内容。

4 个答案:

答案 0 :(得分:2)

这应该有效:

"[a-zA-Z_0-9\s]+"|([a-zA-Z0-9_]+)

这里的想法是,如果单词被“包围”,我们将不会记录匹配。

demo :)

答案 1 :(得分:0)

使用以下正则表达式,然后从组索引1中获取所需的字符串。

@"""[^""]*""|'[^']*'|\b([a-zA-Z_\d]*[a-zA-Z_][a-zA-Z_\d]*)\b"

DEMO

答案 2 :(得分:0)

由于.NET允许可变长度的后视,你可以使用这个正则表达式:

\b\w+\b(?!(?<="[^"\n]*)[^"\n]*")

如果未跟随并且前面有双引号,则匹配单词。

答案 3 :(得分:0)

简化\w匹配字母数字和下划线。

因此\b\w+\b会将一个或多个此类字符与字边界匹配。

如果目标字符串没有出现任何字符(例如,在开头),则避免引号不能简单[^'"]\b\w+…将失败,但负面的后顾则不会。负面前瞻后解决了引用:

(?<!['`"])\b\w+\b(?!['`"])

(因为那些是负面的组,所以不要否定角色类。)

为了不匹配所有数字,可以再次使用前瞻:

(?<!['`"])\b(?!\d+\b)\w+\b(?!['`"])

阐释:

  • 之前的字符不是['"]
  • 字边界
  • 下一个字符边界后面的字符不是全部数字。
  • &#34; Word和#34;字符(这将是匹配
  • 字边界
  • 接下来是引用。

在PowerShell中进行测试:

PS> [regex]::Matches("foo 'asas' bar 123456 ba55z 1xyzzy", "(?>!['`"])\b(?!\d+\b)\w+\b(?!['`"])")

Groups   : {foo}
Success  : True
Captures : {foo}
Index    : 0
Length   : 3
Value    : foo

Groups   : {bar}
Success  : True
Captures : {bar}
Index    : 11
Length   : 3
Value    : bar

Groups   : {ba55z}
Success  : True
Captures : {ba55z}
Index    : 22
Length   : 5
Value    : ba55z

Groups   : {1xyzzy}
Success  : True
Captures : {1xyzzy}
Index    : 28
Length   : 6
Value    : 1xyzzy
    -