【问题标题】:how to write a regular expression for the following scenario?如何为以下场景编写正则表达式?
【发布时间】:2019-05-08 10:28:56
【问题描述】:

我喜欢为下面的场景写一个正则表达式

正则表达式:?

示例 1

输入:

I got good morning message

输出:

good morning

示例 2

输入

good morning message

输出

good morning

示例 3

输入:

my friend got thank you message from xyz

输出:

thank you

忽略其他细节,如i gotmessagemy friend got,输出应该包含消息。消息可以是任何东西,不仅是good morningthank you

【问题讨论】:

  • 可以使用in操作符来完成为什么要使用regex来使事情复杂化?
  • 听起来你在追求 NLP。如果是这样,请尝试 NLTK 或 Spacy。
  • 不,实际上我只需要使用正则表达式...

标签: python regex


【解决方案1】:

如果你想获取got和message关键字之间的字符串,或者如果没有got则从字符串的开头匹配,那么你可以使用以下代码:

import re

pattern = re.compile('(?:.*got )?(?(1)got |)(.*) message')
pattern.search('my friend got thank you message from xyz').group(1)

【讨论】:

    【解决方案2】:

    如果我理解正确,您想在 got 和 message 之间获取消息,或者如果找不到 got,则从字符串的开头获取?

    在这种情况下,您可以使用:

    [^|got ](.*) message
    

    然后您可以通过执行 \1 来提取捕获组(程序或语言可能会有所不同)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多