如何在Python的列表理解中使用regex?

2024-03-29 12:35:25 发布

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

我试图在一个单词列表中找到一个字符串的所有索引位置,我希望这些值作为一个列表返回。如果字符串是独立的,或者它前面或后面有标点符号,我想找到它,但如果它是一个较大单词的子字符串,则不希望找到它。

下面的代码只捕获“cow”,而忽略了“test;cow”和“cow”

myList = ['test;cow', 'one', 'two', 'three', 'cow.', 'cow', 'acow']
myString = 'cow'
indices = [i for i, x in enumerate(myList) if x == myString]
print indices
>> 5

我已尝试将代码更改为使用正则表达式:

import re
myList = ['test;cow', 'one', 'two', 'three', 'cow.', 'cow', 'acow']
myString = 'cow'
indices = [i for i, x in enumerate(myList) if x == re.match('\W*myString\W*', myList)]
print indices

但这会产生一个错误:预期的字符串或缓冲区

如果有人知道我做错了什么,我会很高兴听到的。我有一种感觉,这与我试图在那里使用正则表达式,而它却需要一个字符串有关。有解决办法吗?

我要找的输出应该是:

>> [0, 4, 5]

谢谢


Tags: 字符串代码intest列表for单词one
2条回答

不需要将match的结果赋回x。你的对手应该是x,而不是list

此外,还需要使用re.search,而不是re.match,因为regex模式'\W*myString\W*'与第一个元素不匹配。这是因为test;\W*不匹配。实际上,您只需要测试紧跟和前一个字符,而不需要测试完整的字符串。

因此,您可以在字符串周围使用word boundaries

pattern = r'\b' + re.escape(myString) + r'\b'
indices = [i for i, x in enumerate(myList) if re.search(pattern, x)]

你的代码有一些问题。首先,需要将expr与list元素(x)匹配,而不是与整个列表(myList)匹配。其次,为了在表达式中插入变量,必须使用+(字符串连接)。最后,使用原始文本(r'\W)正确地在expr中插入斜杠:

import re
myList = ['test;cow', 'one', 'two', 'three', 'cow.', 'cow', 'acow']
myString = 'cow'
indices = [i for i, x in enumerate(myList) if re.match(r'\W*' + myString + r'\W*', x)]
print indices

如果myString可能包含特殊的regexp字符(如斜线或点),则还需要对其应用re.escape

regex = r'\W*' + re.escape(myString) + r'\W*'
indices = [i for i, x in enumerate(myList) if re.match(regex, x)]

正如评论中指出的,以下可能是更好的选择:

regex = r'\b' + re.escape(myString) + r'\b'
indices = [i for i, x in enumerate(myList) if re.search(regex, x)]

相关问题 更多 >