正则表达式将由管道划分的单词替换为一个部分

时间:2017-05-08 23:09:59

标签: python regex

我正在查看如下所示的文字:

  

我来这里因为我不得不

我想在冒号前删除子字符串,并用颜色的子字符串替换它。因此,上面的字符串应该看起来像

  

我会来这里因为我必须

我知道我可以使用python循环执行此操作,如下所示,但需要正则表达式的速度

s = "I'm goin|going to be here because I hafta|have to"
for word in s.split():
     if '|' in word:
             word = word.split('|')[1]
     print(word)

我想使用re.sub之类的东西来处理这一行。

3 个答案:

答案 0 :(得分:2)

类似的东西会起作用:

代码:

import re
RE_FRONT_HALF = re.compile(r'\w+\|')

sample = "I'm goin|going to be here because I hafta|have to"
print(RE_FRONT_HALF.sub('', sample))

如何吗

找到一个或多个单词字符,后跟管道|

<强>结果:

I'm going to be here because I have to

答案 1 :(得分:2)

您可以使用匹配1个字符的正则表达式,后跟|符号:

import re
s = "I'm goin|going to be here because I hafta|have to"
s = re.sub(r'\w+\|\b', '', s)
print(s)
# => I'm going to be here because I have to

请参阅Python demo

由于|符号后面始终跟有单词char,因此建议在其后使用\b(单词边界)。这样,您就可以避免匹配one|后跟空格或标点符号(如果您愿意保留它们)。

请参阅regex demo

  • \w+ - 1个或更多(由于+量词)字母字母(字母,数字,_
  • \| - 文字|符号(如果未转义,则表示替换运算符)
  • \b - 一个单词边界。

答案 2 :(得分:2)

请注意\ w也会匹配0-9位数。如果您不想匹配单词中的数字,可以使用:

import re

s = "I'm goin|going to be here because I hafta|have to"

s = re.sub("[a-zA-z]*\|", "", s)

print(s)