【问题标题】:Finding string before certain phrase在某个短语之前查找字符串
【发布时间】:2018-07-05 17:42:26
【问题描述】:

假设表示该短语的字符串是"Holy it is changing again and again"

我想在"again and again"之前打印出"changing"这个词,但是这个词可能每次都不一样。所以我需要提取短语"again and again"之前的单词。不应提取短语 "holy it is"

我怎样才能用 Python 做到这一点?

我曾想过像Python regex to match word before < 这样使用正则表达式,但我不太确定如何正确编码。

【问题讨论】:

  • 尝试`"一次又一次地改变"

标签: python regex string extract


【解决方案1】:

要开始,试试这个正则表达式:"([Cc]hanging) again and again",捕获(changing) 组。额外的[Cc] 解决了"changing" 大写为"Changing" 的情况。

  • 天哪,它一次又一次地改变
  • 一次又一次地改变,它仍然在改变
  • 一次又一次地改变,仍然一次又一次地改变
  • 一次又一次改变一次又一次改变
  • Some more sample regexes

要使用不同的词,请将([Cc]hanging) 替换为另一个词。例如,要在"again and again" 之前捕获"going",请改用([Gg]oing)

  • 我们一次又一次地进行
  • 在多次警告后一次又一次会被禁止!
  • 一次又一次地进行,并且一次又一次地进行,但还是在绕圈子。
  • Some more sample regexes

要匹配后跟"again and again" 的多个不同单词,包括单词的不同形式,请使用union。为了匹配"change""changes""changing""changed""going",并考虑单词大写的情况,分组部分变为([Cc]hange|[Cc]hanges|[Cc]hanging|[Cc]hanged|[Gg]oing)

  • 天啊一次又一次地变了
  • 一次又一次地改变一次又一次的变化还是
  • 我的分数一次又一次地改变,但现在我的分数没有改变或去任何地方!
  • 一次又一次改变,一次又一次,停止改变。
  • 我们将继续一次又一次地改变
  • Some more sample regexes

【讨论】:

  • 这是我回答的第一部分。
【解决方案2】:

要匹配 任何 字后跟 "again and again",请使用此正则表达式:

  • ([\w]*) again and again

如果您想包含更多字符,例如撇号,请将[\w] 替换为[\w'],方括号内的其他字符也类似(有些需要转义)。

  • 天哪,它一次又一次地改变
  • 我们又要玩了,一遍又一遍地玩
  • OMG 一次又一次
  • 让我们再接再厉。我们一次又一次地去!
  • 我一次又一次地roomba'd(需要添加')
  • Foo 一次又一次地变成 A-B-C,Bar 和 Baz。 (需要添加转义的连字符)
  • More sample regexes!

要查找该模式的所有匹配项,请使用

正则表达式match = re.findall("([\w']*) again and again", phrase),其中([\w']*) 是任何单词(单词字符的序列,包括撇号。它返回所有单词的列表,后跟“一次又一次”。

phrase = "Holy it is changing again and again!"
match = re.findall("([\w']*) again and again", phrase)
# match is ['changing']

phrase = "Going again, going again and again, and finishing again and again!"
match = re.findall("([\w']*) again and again", phrase)
# match is ['going', 'finishing']

phrase = "Defeated again and again! I got ninja'd again and again!"
match = re.findall("([\w']*) again and again", phrase)
# match is ['Defeated', "ninja'd"]

【讨论】:

  • 谢谢! match = re.findall("([\w']*) 一次又一次", 短语) 是完美的
  • @xvienxz2 “谢谢”评论最终将构成噪音。相反,通过单击复选标记接受此答案。这也会给你 2 个代表。
【解决方案3】:
import re

text = '''

Holy it is changing again and again
Holy it is not changing again and again
Holy it has changed again and again
Holy it has changed once
Holy it used to change again and again
'''

prog = re.compile(r'(\w+) again and again');
for line in text.splitlines():
  x = prog.search(line)
  if(x): print(x.group(1))

这个输出:

changing
changing
changed
change

【讨论】:

  • "单词每次都不一样" - 可以是任何单词。
  • 是吗? (\w+) 匹配任何单词。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
相关资源
最近更新 更多