简体   繁体   中英

Match a whole string variable using python regex

I am new to python.

I want to write a regex to find a whole string using 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 . 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 .

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:

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 . Which since you are using \b should not be what you want. findall will find all matching strings.
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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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