![](/img/trans.png)
[英]how to increment a whole word match in python using a variable in the regex
[英]Match a whole string variable using python regex
我是 python 的新手。
我想编写一个正则表达式来使用 re.match 查找整个字符串。
例如,
word1=I
word2=U
str_to_match = word1+"[There could be some space in between]"+ word2[this is the end of string I want to match]"
在这种情况下,它应该匹配I[0 or more spaces in between]U
。 它不应匹配abI[0 or more spaces in between]U
或abI[0 or more spaces in between]Ucd
或I[0 or more spaces in between]Ucd
。
我知道您可以使用边界\b
来设置单词边界,但由于 word1 和 word2 之间可能有许多空格,因此整个字符串就像一个变量,而不是一个固定字符串,它对我不起作用:
ret=re.match(r"\b"+word1+r"\s+" +word2+r"\b")
不工作
有谁知道我怎样才能找到匹配这种情况的正确方法? 谢谢!
match 只匹配字符串的开头。 由于您使用的是 \b ,因此这不应该是您想要的。 findall
将查找所有匹配的字符串。
如果您想找到第一个匹配项并测试它是否存在于字符串中,而不是找到所有匹配项,您可以使用search
:
word1 = 'I'
word2 = 'U'
ret = re.findall(rf"\b{word1}\s*{word2}\b"," I U IU I U aI U I Ub")
print(ret)
ret = re.search(rf"\b{word1}\s*{word2}\b"," IUb .I U ")
print(ret)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.