我正在努力寻找获得此正则表达式的正确方法:
\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
目标是尝试仅匹配在大多数常见编程语言中有效变量名称的单词,而不匹配字符串中的任何内容。
答案 0 :(得分:2)
答案 1 :(得分:0)
答案 2 :(得分:0)
由于.NET允许可变长度的后视,你可以使用这个正则表达式:
\b\w+\b(?!(?<="[^"\n]*)[^"\n]*")
如果未跟随并且前面有双引号,则匹配单词。
答案 3 :(得分:0)
简化\w
匹配字母数字和下划线。
因此\b\w+\b
会将一个或多个此类字符与字边界匹配。
如果目标字符串没有出现任何字符(例如,在开头),则避免引号不能简单[^'"]\b\w+…
将失败,但负面的后顾则不会。负面前瞻后解决了引用:
(?<!['`"])\b\w+\b(?!['`"])
(因为那些是负面的组,所以不要否定角色类。)
为了不匹配所有数字,可以再次使用前瞻:
(?<!['`"])\b(?!\d+\b)\w+\b(?!['`"])
阐释:
['"]
在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