gpt4 book ai didi

regex - 如何将c++与单词边界匹配

转载 作者:行者123 更新时间:2023-12-01 10:21:27 25 4
gpt4 key购买 nike

我想将单词“c++”与 Python 3 中的单词边界匹配。但我的猜测是\b 也会在加号上触发。

为了清楚起见,我已简化为以下测试用例:

\bc\+\+\b

我希望我可以保留单词边界但以某种方式更改其设置。

这样做的原因是我想将正则表达式放在 TfidfVectorizer 中的 token_pattern 中,我无法控制它们的使用方式。

Link to online regex tool

最佳答案

影响字符类“行为”的方式非常有限——它们被称为标志:

re.ASCII ... re.VERBOSE

他们是允许 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

最简单的方法可能是将“c++”与前面的单词边界和后面的空格或非单词字符进行匹配。 r'\bc\+\+[\s\W]' 但这也匹配 'c+++'。如果你想专门匹配 'c++' 而不是 'c+++' 你可能想把一个 '\s' 放到你的模式中并扩展它与您允许的其他字符:

r'\b(c\+\+)[\s.,!?]' 

扩展括号中的字符以容纳 c++ 之后允许的更多内容 - 将它们从分组中排除 (c++) 将需要它们匹配但不将它们包含到组中。

至于regex-test工具,可能改成https://regex101.com/ - 它支持 Python,您甚至可以保存 模式和测试文本并提供链接:

https://regex101.com/r/6XtVTS/1

关于regex - 如何将c++与单词边界匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com