为什么Python中的正则表达式不捕获整数?

2024-05-23 15:44:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用正则表达式来查找没有用0x重新固定的数字序列。你知道吗

例如

0
50505
20201
0012

我的正则表达式是(?:[^(0x)]\d+),它(在我的头脑中)转换为匹配任何不是以0x开头的数字序列。但这是行不通的-我错误地做出了什么假设?你知道吗


Tags: 错误序列数字头脑
2条回答

对于任何不以[0或x]开头的内容,它看起来都是非捕获组。你知道吗

你试过从后面看一眼吗?你知道吗

(r'(?<!0x)\d+')

(我花了很长时间才在电话里打这个,现在我看到有人已经整理好了。经验教训:电话里没有regex。)

正则表达式中的[^(0x)]匹配任何不是(0x)的字符。你知道吗

使用负向后看:

>>> re.findall(r'(?<!0x)\d+\b', '0 0x111 50505 20201 0012')
['0', '11', '50505', '20201', '0012']

http://docs.python.org/2/library/re.html

(?<!...)

Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.


更新

使用以下正则表达式:

>>> re.findall(r'\b\d+\b', '0 0x111 50505 20201 0012')
['0', '50505', '20201', '0012']

相关问题 更多 >