如何检查一个字符串是否包含另一个由特殊字符包围的字符串?

问题描述 投票:2回答:3

我将提供一个示例以了解我的意思:

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',因此,如果我用错了它,请纠正我,或者有更好的方法来做。谢谢大家!

python regex special-characters
3个回答
2
投票
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等)


2
投票

在集合[A-Za-z0-9]中搜索在字符“ [[not”之前和之后的“ BPR”:

r'[^A-Za-z0-9]BPR[^A-Za-z0-9]'

0
投票
这里是检测它的方法:

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

© www.soinside.com 2019 - 2024. All rights reserved.