【问题标题】:Ignore part of a line which contains certain text [duplicate]忽略包含某些文本的行的一部分[重复]
【发布时间】:2019-11-11 17:02:11
【问题描述】:

我有一个如下所示的字符串:

https:\\somegif.some\some-random-gif.gif *textinbetween?!@* abc-abc-abc
def-def-def
a something: 123-456-789-101

我需要获取与此 RegEx ([\w]+(\s*-\s*[\w]+){2,3}) 匹配的所有字符串。

这是我用来获取这些字符串的代码:

import re

test_str = ("https:\\\\somegif.some\\some-random-gif.gif *textinbetween?!@* abc-abc-abc\n"
            "def-def-def\n"
            "a something: 123-456-789-101\n")
regex = r"([\w]+(\s*-\s*[\w]+){2,3})"

matches = re.finditer(regex, test_str, re.MULTILINE)

for match in matches:
    match = match.group()
    match = match.replace(" ", "")
    print(match)

这将输出:

some-random-gif
abc-abc-abc
def-def-def
123-456-789-101

我不需要some-random-gif。我该如何过滤它。
我可以使用这样的东西:

nohttp = str()
for line in test_str.split('\n'):
    if 'http' not in line:
        nohttp += line + '\n'

但它也会删除abc-abc-abc

【问题讨论】:

  • 如果你不想匹配重复组中的gif,你可以使用否定的前瞻\w+(?:\s*-\s*(?!gif\b)\w+){2,3}
  • @Thefourthbird some-random-gif 可以是任何东西。我只是用它来举例。
  • @conquistador [\w-]+(?=\n) 怎么样?

标签: python regex


【解决方案1】:

在我看来,当您的正则表达式匹配时,您正试图忽略 url 及其内容 - 这是有道理的,因为 url 可能具有与您的模式匹配的结构。

一种可能的解决方案是在搜索之前使用正则表达式从字符串中删除 url;鉴于 url 的结尾和要匹配的文本的开头之间似乎有空格,您可以匹配从字符串开头开始的非空白字符,检查以确保它们以“http”开头或“https”。

import re

instring = ("https:\\\\somegif.some\\some-random-gif.gif *textinbetween?!@* abc-abc-abc\n"
            "def-def-def\n"
            "a something: 123-456-789-101\n")

newstring = re.sub('^https?:\S*','',instring)

regex = r"([\w]+(\s*-\s*[\w]+){2,3})"

matches = re.finditer(regex, newstring, re.MULTILINE)

for match in matches:
    match = match.group()
    match = match.replace(" ", "")
    print(match)

Demo

如果 URL 始终出现在您的测试字符串中并且始终是第一个“单词”,您可以简单地使用 ^\S*

【讨论】:

    【解决方案2】:

    不知道为什么some-random-gif 不应该匹配。

    这将匹配空格边界之间的项目:

    (?<!\S)[\w]+(?:\s*-\s*[\w]+){2,3}(?!\S)

    https://regex101.com/r/v7cMAv/1

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 2021-07-08
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      相关资源
      最近更新 更多