我想在识别一个子串后提取并构造一些字符串,该子字符串与方形braquets中包含的模式相匹配:
e.g: if my text is '2 cups [9 oz] [10 g] flour '
i want to generate 4 strings out of this input:
- "2 cups" -> us
- "9 oz" -> uk imperial
- "10 g" -> metric
- "flour" -> ingredient name
作为一个开始,我已经开始识别任何包含oz关键字的方形braquet,并编写了以下代码,但匹配没有发生。有什么想法和最佳实践来实现这一点?在
p_oz = re.compile(r'\[(.+) oz\]', re.IGNORECASE) # to match uk metric
text = '2 cups [9 oz] flour'
m = p_oz.match(text)
if m:
found = m.group(1)
print found
我只是在扩展布伦巴恩接受的答案。我喜欢午餐时解决一个好问题。以下是我对你的问题的全面理解:
给定字符串
2 cups [9 oz] [10 g] flour
将返回字符串数组:
^{pr2}$您需要使用
search
而不是match
。在re.match
尝试根据正则表达式匹配整个输入字符串。那不是你想要的。您希望找到与正则表达式匹配的子字符串,这就是re.search
的用途。在相关问题 更多 >
编程相关推荐