【问题标题】:Python : Regex capturing genric for 3 cases.Python:正则表达式捕获 3 种情况的泛型。
【发布时间】:2016-12-22 10:22:42
【问题描述】:

嗨,任何人都可以帮助我改善我不工作的常规表达。

字符串案例:

1) 120 磅,适用于年龄 8 岁及以上的骑手。 #catch : 8 岁及以上

2) 56w x 28d x 32h 英寸推荐给 12 岁及以上 的爱好者。 #catch : 12 岁及以上

3) 4 位用户录制语音以有效使用语言辅导舱尺寸为 11l x 9w x 5h 英寸,建议 6 岁及以上 使用。 #catch : 6 及以上

我想要一个通用正则表达式,它对所有三个字符串都适用。

我的正则表达式是:

\b\d+[\w+\s]?(?:\ban[az]\sup\b|\ban[az]\sabove\b| \ban[az]\sold[az]*\b|\b&\sup)

但它运行得不是很好。如果有人可以为我提供通用正则表达式,它适用于所有 3 种情况我正在使用 python re.findall()

有人吗?可以帮忙吗?

【问题讨论】:

  • 希望对您有所帮助,re.search(r'(?is)ages\s*(.*?)\.$',s).group(1)
  • 如果您的示例说明了所有可能的字符串(但我担心它们没有;)您可以像\d+[^\d]*$ 一样简单地做到这一点。 See it at regex101。它匹配最后一个数字和它之后的所有内容。或者更复杂一点 - 确保前面有 age - here
  • 实际上,还不清楚哪种 generic 模式适合您,因为只有 3 个示例并且没有提供规范。只能猜测您真正需要什么。
  • \d+[^\d]*$ 是救世主,谢谢 :-D。 G类。我不知道为什么人们在这里给出负面评价。我有一个问题我质疑。就这样。感谢人们的回答。美好的一天!

标签: python regex findall


【解决方案1】:

养成习惯,从冗长的正则表达式开始:

import re
rx = re.compile(r'''
    ages\                                # look for ages
    (\d+(?:\ years)?\ and\ (?:above|up)) # capture a digit, years eventually
                                         # and one of above or up
''', re.VERBOSE)

string = '''
1) 120 lbs and is intended for riders ages 8 years and up. #catch : 8 years and up
2) 56w x 28d x 32h inches recommended for hobbyists recommended for ages 12 and up. #catch : 12 and up
3) 4 users recorded speech for effective use language tutor pod measures 11l x 9w x 5h inches recommended for ages 6 and above. #catch : 6 and above
'''

matches = rx.findall(string)
print(matches)
# ['8 years and up', '12 and up', '6 and above']


请参阅 a demo on ideone.com 以及 regex101.com

【讨论】:

    【解决方案2】:

    (由于我在评论中提出的建议似乎是您想要的,因此我将其作为答案。)

    如果您的示例说明了所有可能的字符串(但我担心它们没有;)您可以像这样简单地做到这一点

    \d+[^\d]*$
    

    See it here at regex101.

    它匹配最后一个数字,以及它之后的所有内容。

    或者更复杂一点 - 确保前面有年龄 - here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2017-01-25
      • 2019-01-12
      • 1970-01-01
      相关资源
      最近更新 更多