Python 正则表达式带有 % 符号的单词边界

问题描述 投票:0回答:2

我想检测所有

1%
作为带有单词边界的子字符串。使用 python 中的以下代码片段不会返回任何内容。我想检测前两个 1% 子字符串,但不是最后一个单词 0.1% 的一部分的 1%。这就是为什么单词边界很重要。

matches = re.finditer(r'\b1%\b', '1% of 100 is not 1% of 10 its 0.1%', re.I)
for match in matches:
    print(match)

有什么想法吗?

python regex
2个回答
0
投票

来自 python

re
文档

请注意,正式地,

\b
被定义为
\w
和 a 之间的边界
\W
字符(反之亦然),或位于
\w
与开头或结尾之间 字符串的。

观察到数字属于

\w
,点属于
\W
,因此
.1
内部有边界,
%
和空格都属于
\W
,因此
% 

内部没有边界

您可以使用负向后查找来排除以点为前缀的 1,如下所示

import re
matches = re.finditer(r'(?<![.])1%', '1% of 100 is not 1% of 10 its 0.1%', re.I)
for match in matches:
    print(match)

提供输出

<re.Match object; span=(0, 2), match='1%'>
<re.Match object; span=(17, 19), match='1%'>

请注意,我使用

[.]
作为文字点是必需的,而不是表示任何字符的点。


0
投票

由于

.
1
都被视为“非单词字符”,因此
.
1
之间没有单词边界。

您必须结合使用“行首”和“查找空白”。

像这样:

(?:^|\s)1%

分解:

(?:     # Start of non-capturing group
^       # Beginning of line
|       # or
\s      # a single whitespace
)       # End of non-capturing group
1%      # Literal string to match

在这里测试:https://regex101.com/r/sVa6U4/1

© www.soinside.com 2019 - 2024. All rights reserved.