[英]Python Regex match if string has X amount of words that start with @#$:
我要尝试的是匹配字符串,如果该字符串包含X量(假设为5)以@#$:字符开头的单词。
假设X为5的示例:
@someword someotherword anotherword word1 word2 word3 => false
@someword :someotherword #anotherword $word1 word2 word3 => false
@someword :someotherword #anotherword $word1 #word2 $word3 => true
您可以使用此正则表达式,前提是这些符号仅在单词字符之前使用:
(?:]\B[@#$:]\w+[^@#$:]*){5}
码:
>>> arr = ['@someword someotherword anotherword word1 word2 word3',
'@someword :someotherword #anotherword $word1 word2 word3',
'@someword :someotherword #anotherword $word1 #word2 $word3']
>>> reg = re.compile(r'(?:\B[@#$:]\w+[^@#$:\n]*){5}');
>>> for i in arr:
... print(reg.findall(i))
...
[]
[]
['@someword :someotherword #anotherword $word1 #word2 ']
\\B
:匹配\\b
不匹配的地方。 [@#$:]\\w+
:匹配以[@#$:]
开头的1+个单词字符 [^@#$:]*
:匹配0个或多个不包含[@#$:]
字符 (...){5}
:在当前输入中匹配其中的5个 像这样吗
import re
my_re = '[#@$:][a-zA-Z]*'
my_string = "#hello :my #name $is $stef"
print(len(re.findall(my_re,my_string)) >= 5)
积极向前看是做到这一点的一种方法:
input = "@someword :someotherword #anotherword $word1 #word2 $word3"
result = re.match(r'.*((?<=\s)|(?<=^))[@#$:]\S+.*(\s[@#$:]\S+.*){4}', input)
if result:
print("Found a match")
这个问题很棘手,因为您想将单词以一个特殊符号[@#$:]
开头。 但是,我们不能仅使用单词边界\\b
,因为特殊字符不是单词字符。 因此,我们可以检查目标词开头之前的内容是空格还是字符串的开头。
正确的正则表达式为((?:[@#$].+){5})
。 正则表达式说明
例:
import re
...
tst = """
@someword someotherword anotherword word1 word2 word3
@someword :someotherword #anotherword $word4 #word5 $word6
@someword :someotherword #anotherword $word1 word2 word3
@someword :someotherword #anotherword $word1 #word2 $word3
"""
res = re.findall(r"((?:[@#$].+){5})", tst)
print(res)
结果:
['@someword :someotherword #anotherword $word4 #word5 $word6', '@someword :someotherword #anotherword $word1 #word2 $word3']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.