简体   繁体   English

使用 python 正则表达式匹配整个字符串变量

[英]Match a whole string variable using python regex

I am new to python.我是 python 的新手。

I want to write a regex to find a whole string using re.match.我想编写一个正则表达式来使用 re.match 查找整个字符串。

For example,例如,

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]"

In this case, it should match I[0 or more spaces in between]U .在这种情况下,它应该匹配I[0 or more spaces in between]U It shouldn't match abI[0 or more spaces in between]U , OR abI[0 or more spaces in between]Ucd , OR I[0 or more spaces in between]Ucd .它不应匹配abI[0 or more spaces in between]UabI[0 or more spaces in between]UcdI[0 or more spaces in between]Ucd

I know you could use boundary \b to set the word boundary but since there could be a number of spaces in between word1 and word2, the whole string is like a variable, not a fixed string, it won't work for me:我知道您可以使用边界\b来设置单词边界,但由于 word1 和 word2 之间可能有许多空格,因此整个字符串就像一个变量,而不是一个固定字符串,它对我不起作用:

ret=re.match(r"\b"+word1+r"\s+" +word2+r"\b")

not working不工作

Does anyone know how could I find the correct way to match this case?有谁知道我怎样才能找到匹配这种情况的正确方法? Thanks!谢谢!

match only matches at the beginning of the string . match 只匹配字符串的开头 Which since you are using \b should not be what you want.由于您使用的是 \b ,因此这不应该是您想要的。 findall will find all matching strings. findall将查找所有匹配的字符串。
If you want to find the first occurrence and just test if it exists in the string, and not find all matches you can use search :如果您想找到第一个匹配项并测试它是否存在于字符串中,而不是找到所有匹配项,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM