如何检查一个字符串是否包含另一个被特殊字符包围的字符串?
How to check if a string contains another string surrounded by special characters?
我举个例子看看我的意思:
my_string1='005010X221A1~ST*835*0001~BPR*I*642.65*C*'
my_string2='005010X221A1~ST*835*0001~BPRI*642.65*C*'
我想知道什么时候 "BPR" 两边都有特殊字符,特殊字符是指除字母或数字以外的所有字符。
我尝试了以下方法,但它不起作用,因为它 returns 两个字符串都是假的,而我需要字符串 1 为真:
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*')
那里的正则表达式找到一个 不是 A 到 Z、a 到 z 或 0 到 9 后跟 BPR 等的字符。
检测方法如下:
my_string1='005010X221A1~ST*835*0001~BPR*I*642.65*C*'
my_string2='005010X221A1~ST*835*0001~BPRI*642.65*C*'
def check(string):
if not string[string.index('BPR')-1].isalnum() and not string[my_string1.index('BPR')+len('BPR')].isalnum():
return True
else:
return False
print(check(my_string1))
print(check(my_string2))
输出:
True
False
我举个例子看看我的意思:
my_string1='005010X221A1~ST*835*0001~BPR*I*642.65*C*'
my_string2='005010X221A1~ST*835*0001~BPRI*642.65*C*'
我想知道什么时候 "BPR" 两边都有特殊字符,特殊字符是指除字母或数字以外的所有字符。
我尝试了以下方法,但它不起作用,因为它 returns 两个字符串都是假的,而我需要字符串 1 为真:
res=False
if re.search(r'(BPR(?<=/D)|BPR(?<=/W))&(BPR(?=\D)|BPR(?=\W))',my_string1) != None:
res=True
我从来没有用过're',所以如果我用错了,请指正,或者有更好的方法。谢谢大家!
在集合 [A-Za-z0-9]
:
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*')
那里的正则表达式找到一个 不是 A 到 Z、a 到 z 或 0 到 9 后跟 BPR 等的字符。
检测方法如下:
my_string1='005010X221A1~ST*835*0001~BPR*I*642.65*C*'
my_string2='005010X221A1~ST*835*0001~BPRI*642.65*C*'
def check(string):
if not string[string.index('BPR')-1].isalnum() and not string[my_string1.index('BPR')+len('BPR')].isalnum():
return True
else:
return False
print(check(my_string1))
print(check(my_string2))
输出:
True
False