【问题标题】:regex search remove word正则表达式搜索删除单词
【发布时间】:2020-01-25 22:09:57
【问题描述】:

我想删除段落中的前 4 个单词

原文:Mywebsite 21 12 34 have 10000 traffic

我想要的结果:have 10000 traffic

我有 1000 行与原始段落相同(Mywebsite 21 12 34 have 10000 traffic

我有这样的正则表达式搜索代码:

下面的代码是从句子中删除第一个单词:

^\w+\s+(.*)  = replace with $1

以下代码将删除行中的所有数字:

[0-9 ]+  = replace with space

我想结合上面的代码,让一个正则表达式搜索代码按照我上面的解释工作,但不影响同一行的任何其他单词。

【问题讨论】:

  • 尝试^\w+\s[\d\s]+并用空字符串替换,re.sub(r'^\w+\s[\d\s]+', '', text)
  • 或者尝试删除 4 次非空白字符,后跟一个制表符或空格 ^[\t ]*(?:\S+[ \t]+){4} regex101.com/r/CyUYh0/1
  • 完美!!它的工作很迷人,非常感谢!
  • regex.inginf.units.it 这是构建正则表达式的好工具。

标签: python regex regex-negation regex-greedy


【解决方案1】:

你可以使用

re.sub(r'^(\w+\s)[\d\s]+', r'\1', text)

regex demo 模式将匹配

  • ^ - 字符串开头
  • (\w+\s) - 捕获组 1:一个或多个单词字符和一个空格
  • [\d\s]+ - 1+ 个空格或数字字符。

Python demo:

import re
rx = re.compile(r"^(\w+\s)[\d\s]+")
s = "Mywebsite 21 12 34 have 10000 traffic"
print( rx.sub(r"\1", s) ) # => Mywebsite have 10000 traffic

【讨论】:

  • ^\w+\s[\d\s]+ 这个工作完美,我怎么能在第一个单词示例 21 12 34 之后只删除数字?但只有那个数字
  • @GayanFernando 查看更新的解决方案,如果它适合您,请考虑接受。
【解决方案2】:

如果你的行都是完全相同的格式,即如果你总是需要删除前 4 个单词,你可以做这样的事情,这比 RegEx 更容易理解:

# Iterate through all your lines
for line in lines:

    # Split the line string on spaces to create an array of words.
    words = line.split(' ')

    # Exclude the 4 first words and re-join the string with the remaining words.
    line = ' '.join(words[4:])

【讨论】:

    【解决方案3】:

    您尝试的模式^\w+\s+(.*) 匹配 1+ 个单词字符、1+ 个空白字符,然后匹配除换行符之外的任何字符,直到字符串末尾,这样将匹配整个字符串。

    要删除第一个单词和后面的 3 次 2 数字,您可以使用:

    ^\s*\w+(?: \d{2}){3}\s*
    
    • ^ 字符串开始
    • \s* 匹配 0+ 个空白字符
    • \w+ 匹配 1+ 个单词字符
    • (?: \d{2}){3} 重复 3 次匹配一个空格和 2 个数字
    • \s* 匹配 0+ 个空格字符

    Regex demo | Python demo

    请注意,\s 也匹配换行符。如果您只想匹配空格或制表符,您可以改用[ \t]

    【讨论】:

    • 谢谢你,^\w+\s[\d\s]+ 这个作品完美!但是现在我只想在第一个单词之后删除那个数字,例如 Mywebsite 有 10000 流量?
    • 其实我破解后 (?: \d{2}){3}\s* 这个对我有用。因为我也只想删除数字
    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 2012-03-10
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2021-08-07
    • 2015-03-16
    • 1970-01-01
    相关资源
    最近更新 更多