我正在尝试匹配一个字符串中的多个子字符串。
兴趣领域的格式为:
Sample1: "text text text[One]"
Sample2:"text text text[One/Two]"
Sample3:"text text text[One/Two/Three]"
我正在尝试通过以下方式使用正则表达式获取数字列表:
numbers = re.findall('(\[|\/)(\w+)(\/|\])', str)
然而,group2 产生:
#Sample1
['One']
#Sample2
['One']
#Sample3
['One','Three']
无论如何,我无法让它匹配“/”和“]”或“/”之间的第二个数字。但是,我不明白为什么它不匹配“/Two/”,因为“/”字符在两种选择中都是一个选项。
我还尝试使用以下正则表达式以不同的方式构建它:
re.findall('[\[]?[\/]?(\w+)[\/]?[\]]?', str)
虽然它给了我想要的结果,但它也给了我前面文本中的所有单词。
感谢任何建议。
最佳答案
使用 lookbehind 和 lookahead 所以 [
, /
和 ]
不是匹配的一部分:
>>> [re.findall('(?<=\[|\/)\w+(?=\/|\])', s) for s in samples]
[['One'], ['One', 'Two'], ['One', 'Two', 'Three']]
这样,中间的/
可以用于两次匹配。
关于Python Regex bool 值 'or' 不选择所有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936768/