我将提供一个示例以了解我的意思:
my_string1='005010X221A1~ST*835*0001~BPR*I*642.65*C*'
my_string2='005010X221A1~ST*835*0001~BPRI*642.65*C*'
我想知道“ BPR”何时在两侧都有特殊字符,用特殊字符表示不是字母或数字的所有内容。
我尝试了以下操作,但由于两个字符串都返回False,并且string1我需要True,所以它不起作用:
res=False
if re.search(r'(BPR(?<=/D)|BPR(?<=/W))&(BPR(?=\D)|BPR(?=\W))',my_string1) != None:
res=True
我以前从未使用过're',因此,如果我用错了它,请纠正我,或者有更好的方法来做。谢谢大家!
在集合[A-Za-z0-9]
中搜索在字符“ [[not”之前和之后的“ BPR”:
r'[^A-Za-z0-9]BPR[^A-Za-z0-9]'
In [1]: import re
In [2]: re.search('[^A-Za-z0-9]BPR[^A-Za-z0-9]', '005010X221A1~ST*835*0001~BPR*I*642.65*C*')
Out[2]: <re.Match object; span=(24, 29), match='~BPR*'>
In [3]: re.search('[^A-Za-z0-9]BPR[^A-Za-z0-9]', '005010X221A1~ST*835*0001~BPRI*642.65*C*')
找到正则表达式的字符是not A到Z,a到z或0到9,然后是BPR等)
def isMatch(string):
return re.search(r'(?<=\W)BPR(?=\W)', string) != None
示例:
print(isMatch(my_string1)) print(isMatch(my_string2))
此打印:
True False
您可以测试正则表达式here
。
here