【发布时间】: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)怎么样?