我希望匹配单词" c ++"在Python 3中使用单词边界。但我的猜测是\ b也会在加号上触发。
为了清楚起见,我已简化为以下测试用例:
\bc\+\+\b
我希望我可以保留单词边界,但不知何故更改其设置。
这样做的原因是我想将正则表达式放在一个tfidfVectorizer中的token_pattern中,我无法控制它们如何使用它。
答案 0 :(得分:1)
如何影响字符类的“行为”的方式非常有限 - 它们被称为标志:
re.ASCII ... re.VERBOSE
他们f.e.允许r'.'
匹配换行符(re.DOTALL
),更改^$
(re.MULTILINE
)的行为或使您的正则表达式匹配,而不会感知案例(re.IGNORECASE
)。
他们都没有将\b
更改为没有'+'
。如果您想将c++
与wordboundaries匹配,则必须模仿您的模式中的\b
- 行为:
\b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.
来源:https://docs.python.org/3/library/re.html#regular-expression-syntax
最简单的可能是使用之前的单词边界的mach'c ++'以及之后的空格或非单词字符。 r'\bc\+\+[\s\W]'
但这也符合'c+++'
。如果您想完全匹配'c++'
而不是'c+++'
,则可能需要在模式中添加'\s'
并将其与您允许的其他字符一起扩展:
r'\b(c\+\+)[\s.,!?]'
扩展bracked中的字符以容纳c ++后允许的更多内容 - 将它们从分组中排除(c ++)将需要它们匹配但不包括在组中。
对于正则表达式测试工具,可能更改为https://regex101.com/ - 它具有python支持,您甚至可以保存模式和测试文本并提供链接: