【发布时间】:2016-02-06 01:02:02
【问题描述】:
我正在尝试使用正则表达式来查找字符串中括号之间的特定字符串,如下所示:
foo = '((peach W/O juice) OR apple OR (pear W/O water) OR kiwi OR (lychee AND sugar) OR (pineapple W/O salt))'
具体来说,我只想找到(peach W/O juice)、(pear W/O water) 和(pineapple W/O salt)。
我尝试了lookahead 和lookbehind,但无法获得正确的结果。
例如,当我执行以下 RegEx 时:
import re
regex = '(?<=[\s\(])\([^\)].*\sW/O\s[^\)].*\)(?=[\)\s])'
re.findall(regex, foo)
我得到了整个字符串:
['(peach W/O juice) OR apple OR (pear W/O water) OR kiwi OR (lychee AND sugar) OR (pineapple W/O salt)']
编辑:
我发现了问题:
我应该使用[\)]* 而不是[\)].*,这会给我正确的结果:
regex = '(?<=[\s\(])\([^\)]*\sW/O\s[^\)]*\)(?=[\)\s])'
re.findall(regex, foo)
['(peach W/O juice)', '(pear W/O water)', '(pineapple W/O salt)']
【问题讨论】:
-
建议:把引号里面的字符串全部找出来,然后用
if 'W/O' in string过滤出你想要的字符串怎么样?
标签: python regex python-2.7 lookahead lookbehind