【问题标题】:I would like to retrieve the words between an amount and the first word in uppercase with a regex我想用正则表达式检索金额和第一个大写单词之间的单词
【发布时间】:2021-09-04 07:36:18
【问题描述】:

我目前正在使用正则表达式。我知道如何使用正则表达式检索欧元金额:

r'[+-]?(?:[0-9]*[,])?[0-9]+'

我也知道如何用大写字母检索单词:

r'\b[A-Z]+(?:\s+[A-Z]+)*\b'

但我似乎没有让以下工作。检索欧元金额和 Capital 中第一个 WORD 之间的单词。例如,如果我有以下句子:

€10,95 Hello how are you doing? good or, bad? WORD 

我想检索:“你好,你好吗?好还是不好?”

感谢任何帮助。

【问题讨论】:

  • 把(.+?)放在两个模式之间。该捕获组将捕获介于两者之间的单词。
  • re.search(r'\d*,?\d+\s*(.*?)\s*\b[A-Z]+\b', text).group(1)?见regex101.com/r/MpCckx/3
  • 你如何定义“单词”?包括标点符号吗?特殊字符、数字呢?
  • @WiktorStribiżew 谢谢你的回答。我更喜欢 Wiktor 的回答,因为它更紧凑。但需要稍微研究一下他的答案。

标签: regex


【解决方案1】:

使用您显示的示例,请尝试以下正则表达式。用 Python3x 编写和测试。

import re
text = '€10,95 Hello how are you doing? good or, bad? WORD '
val=re.search(r'€\d+(?:,\d+)?\s*(.*?)(?=\s+[A-Z])', text)
print(val.group(1))
Hello how are you doing? good or, bad?

Online demo for above regex

说明:为上述正则表达式添加详细说明。

€\d+          ##Matching € character following 1 or more digits here.
(?:,\d+)?\s*  ##In a non-capturing group matching comma followed by 1 or more digits keeping it optional followed by 0 or more spaces.
(.*?)         ##Creating 1st(and only) capturing group with lazy match here.
(?=\s+[A-Z])  ##Doing positive look ahead to make sure its followed by spaces then capital letters.

【讨论】:

    【解决方案2】:

    你可以试试这个表达式:

    r'(?<=\d\s).*?(?=\s[A-Z])'
    

    它使用:

    lookbehind:必须以数字和空格开头。

    lookahead:必须以大写字符结尾。

    【讨论】:

    • 如果您使用环视,您可能会省略捕获组并使用.*?
    【解决方案3】:

    你可以使用

    \d*,?\d+\s*(.*?)\s*\b[A-Z]+\b
    

    请参阅regex demo。 详情:

    • \d* - 零个或多个数字
    • ,? - 一个可选的,
    • \d+ - 一位或多位数字
    • \s* - 零个或多个空格
    • (.*?) - 第 1 组:除换行符之外的任何零个或多个字符,尽可能少
    • \s* - 零个或多个空格
    • \b[A-Z]+\b - 一个或多个大写 ASCII 字母作为整个单词(\b 是单词边界)。

    查看 Python 演示:

    import re
    text = '€10,95 Hello how are you doing? good or, bad? WORD '
    m = re.search(r'\d*,?\d+\s*(.*?)\s*\b[A-Z]+\b', text)
    if m:
        print(m.group(1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2020-06-09
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多