How to check if a string contains another string surrounded by special characters?

Viewed 298

I'll provide an example to see what I mean:

my_string1='005010X221A1~ST*835*0001~BPR*I*642.65*C*'
my_string2='005010X221A1~ST*835*0001~BPRI*642.65*C*'

I want to know when "BPR" has special characters from both sides, by special characters I mean everything that is not a letter or digit.

I tried the following, but it doesn't work because it returns False for both strings, and I need True for string1:

res=False

if re.search(r'(BPR(?<=/D)|BPR(?<=/W))&(BPR(?=\D)|BPR(?=\W))',my_string1) != None:

    res=True

I never used 're' before, so if I'm using it wrong, please correct me, or if there is a better way to do it. Thanks, everyone!

3 Answers

Search for "BPR" preceded by and followed by a character not in the set [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*')

The regex there is find a character that is not A through Z, a through z, or 0 through 9 followed by BPR, etc.

Here's way way to detect it:

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))

Output:

True
False
Related