我正在使用Python3,并尝试使用正则表达式将模式与变量中的值匹配。发布之前,我查看了:
How to use variables in Python regular expression
-和-
How to use a variable inside a regular expression?
这里是代码:
import re
x = []
x.append("test")
x.append("me")
x.append(x[0] + x[1])
TEXTO = x[2]
print(TEXTO)
if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", "StM", re.IGNORECASE):
print("Successful match")
else:
print("Match attempt failed")
if re.search('(.+)'+TEXTO+'(.+)', "StM", re.IGNORECASE):
print("Successful match")
else:
print("Match attempt failed")
并且仍然失败。收到的两个输出均为“尝试匹配失败”
[dogzilla@localhost ~]$ python3 py1.py
testme
Match attempt failed
Match attempt failed
将有问题的变量(TEXTO)放入搜索方法的正确方法是什么?
谢谢!
更改参数的顺序:
if re.search('StM', TEXTO, re.IGNORECASE):
print("Successful match")
else:
print("Match attempt failed")