【问题标题】:usage of regular expression in PythonPython中正则表达式的使用
【发布时间】:2016-11-21 14:08:19
【问题描述】:

我尝试通过这种模式使用正则表达式解析字符串

text1 (text2 500g OR kg text3) text4

示例

1.tomato (more 500g)
2.potatoes (1 kg) 
3.potatoes (10 kg) onion

我如何使用重新提取 text1+text4

1. tomato
2. potatoes
3. potatoes onion

【问题讨论】:

  • 您的示例似乎与您的要求不一致 - 您已经注意到您需要 text1 和 text2,但您的示例 #3 显示 text1 和 text4。考虑让这个问题更清楚。

标签: regex python-3.x expression


【解决方案1】:

下面的答案只是匹配文本并使用组提取子文本

数据:

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]

【讨论】:

  • 谢谢。它可以工作,但是当 inside () 不是 kg 或 g 时,表达式不能匹配。示例“4.potatoes (10 abc) onion” - 不匹配
  • @AlexanderVedmed',请确保在您的问题中包含这些类型的限制;)我将该条件添加到上述正则表达式中。
猜你喜欢
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 2014-03-30
  • 2010-09-12
  • 2011-08-06
  • 2013-03-24
  • 2020-09-14
相关资源
最近更新 更多