Python Regex match if string有X个以@#$开头的单词:

2024-09-27 07:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做的是匹配字符串,如果该字符串包含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

Tags: 字符串falsetrue示例字符单词word1word2
3条回答

积极的展望将是实现这一目标的一种方法:

input = "@someword :someotherword #anotherword $word1 #word2 $word3"
result = re.match(r'.*((?<=\s)|(?<=^))[@#$:]\S+.*(\s[@#$:]\S+.*){4}', input)

if result:
    print("Found a match")

这个问题很棘手,因为您想用一个特殊的符号[@#$:]来匹配单词。但是,我们不能只使用单词边界\b,因为特殊字符不是单词字符。因此,我们可以检查在目标项开始之前的是空格,还是字符串的最开始。你知道吗

您可以使用此正则表达式,前提是这些符号仅在单词字符之前使用:

(?:]\B[@#$:]\w+[^@#$:]*){5}

RegEx Demo

代码:

>>> 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)

相关问题 更多 >

    热门问题