Regex 正则表达式在Python中的使用
我尝试通过这种模式使用正则表达式解析字符串 text1(text2500g或kg text3)text4 示例 如何使用重新提取文本1+文本4Regex 正则表达式在Python中的使用,regex,python-3.x,expression,Regex,Python 3.x,Expression,我尝试通过这种模式使用正则表达式解析字符串 text1(text2500g或kg text3)text4 示例 如何使用重新提取文本1+文本4 下面的答案仅与文本匹配,并使用组提取子文本 数据: strings = ["1.tomato (more 500g)", "2.potatoes (1 kg)", "3.potatoes (10 kg) onion", "4.potatoes (10 abc) onion"] 编写一个方便的函数: def find_substrings(s):
下面的答案仅与文本匹配,并使用组提取子文本 数据:
strings = ["1.tomato (more 500g)",
"2.potatoes (1 kg)",
"3.potatoes (10 kg) onion",
"4.potatoes (10 abc) onion"]
编写一个方便的函数:
def find_substrings(s):
#remove spaces for convenience
s = re.sub(" ", "", s)
#the regular expression
match = re.search("([\w\.]+)\([\w]+[kg]\)([\w]+)?", s)
#what to return when there is a match
if match:
return(" ".join([x for x in match.groups() if x]))
这将产生以下结果:
In [6]: [find_substrings(x) for x in strings]
Out[6]: ['1.tomato', '2.potatoes', '3.potatoes onion', None]
你的例子似乎与你的要求不符——你已经注意到你想要文本1和文本2,但是你的例子3显示了文本1和文本4。考虑让这个问题更清楚。谢谢。它可以工作,但当inside()不是kg或g时,表达式不能匹配。示例“4.土豆(10 abc)洋葱”-否match@AlexanderVedmed,请确保在问题中包含这些类型的限制;)我将该条件添加到上面的正则表达式中。
def find_substrings(s):
#remove spaces for convenience
s = re.sub(" ", "", s)
#the regular expression
match = re.search("([\w\.]+)\([\w]+[kg]\)([\w]+)?", s)
#what to return when there is a match
if match:
return(" ".join([x for x in match.groups() if x]))
In [6]: [find_substrings(x) for x in strings]
Out[6]: ['1.tomato', '2.potatoes', '3.potatoes onion', None]