How to split a string by another string if it is surrounded by specific characters

Viewed 53

For example I have:

string = 'ST8*010A1~BHT*0019*0 BHT#5*20190114*'

I need to split it by "BHT" only if the character before is "~" and the character after is non-numeric and non-alphabetic and not a space.

I tried this:

new_list = []
new_list = re.split(r'[~]BHT[^A-Za-z0-9 ]', contents)

The issue is that it gives this:

new_list = ['ST8*010A1', '0019*0 BHT#5*20190114*']

I need:

new_list = ['ST8*010A1~', '0019*0 BHT#5*20190114*']

Is there a way to rewrite the code, so it keeps "~"?

Thank you.

1 Answers

You may use

new_list = re.split(r'(?<=~)BHT[^A-Za-z0-9 ]', contents)

See the Python demo yielding ['ST8*010A1~', '0019*0 BHT#5*20190114*'].

Here is a regex demo. The (?<=~) pattern is a positive lookbehind that only checks for a ~ presence in the string, but it is not consumed, and thus remains in the split chunks.

Related