如何让我的正则表达式处理三个用连字符分隔的特定数字?



当我有 3 个用连字符分隔的特定数字时,我试图让这个正则表达式工作。正则表达式在没有连字符时工作。谁能告诉我我能做些什么来解决这个问题。我尝试了\d + -的组合,但我尝试的任何东西都没有奏效。谢谢。

此示例中的数字为 012。我正在尝试让正则表达式匹配 0-1-2 的所有组合。

进口再

fname = ('regextest.txt'(

fh = 打开(fname(

RegEx012 = re.compile(r'\b(?=[1-9]*0((?=[02-9]*1((?=[013-9]*2(\d+\b'(

对于 i 在 FH 中:

if RegEx012.findall(i):
print(i)

文件中的数据:

0-1-2

0-1-4

0-2-1

0-4-1

1-0-2

1-0-4

1-2-0

1-4-0

2-0-1

2-1-0

4-0-1

4-0-2

4-1-0

期望的结果:

0-1-2
0-2-1
1-0-2
1-2-0
2-0-1
2-1-0

我的理解是,对于给定的字符串,我们要匹配大小为 5 的每个子字符串,该子字符串是字符串'012'中字符的排列,第一个和第二个数字之间有一个连字符,第二个和第三个数字之间有一个连字符。

例如,对于字符串:

There are 2-1-0 reasons to buy 1-2-0 dogs, but only 1-2-1 to buy 0-2-1 cats

2-1-01-2-00-2-1(但不是1-2-1(将匹配。

这可以通过以下正则表达式来完成:

r'b(([012])-(?!2)([012])-(?!2|3)[012])b'

正则表达式演示<>̄\_(ツ)_/̄Python 演示

b            : assert word boundary
(             : begin capture group 1
([012])     : match one char in class in capture group 2
-           : match '-'
(?!2)      : negative lookahead asserts next char does not
equal the contents of capture group 
([012])     : match one char in class in capture group 3
-           : match '-'
(?!2|3)   : negative lookahead asserts next char does not
equal the contents of capture group 2 or 3
[012]       : match one char in class
)             : end capture group 1
b            : assert word boundary

捕获组 1 用于捕获匹配项,对于re.findall是必需的,因为还有其他捕获组。

最新更新