Ignoring cases in a regex split based on surrounding characters

Viewed 269

I have a string that I want to split by certain special characters. But I don't want to split anything inside square brackets. How can I set up my regex to ignore cases inside square brackets?

formula = '[var1]+[v/ar/2]^var3/var4' #assume no spaces in the formula
re.split('[-+*/&,^%]',formula) #produces ['[var1]', '[v', 'ar', '2]', 'var3', 'var4']

Desired output:

['[var1]', '[v/ar/2]', 'var3', 'var4']

I think I need to use some fancy negative lookbehind and negative lookahead, but I haven't found a working combination yet.

3 Answers

If you want to use split, you can use an alternation to either capture the content that you want to keep after the split in group 1, or match where you want to split on.

In the result, remove the empty strings from the result.

  • (\[[^][]*]) Capture group 1, capture from an opening till closing square bracket
  • | Or
  • [-+*/&,^%] Match any of the listed characters you want to split on

Regex demo | Python demo

Example

import re

s="[var1]+[v/ar/2]^var3/var4"
result = list(filter(None, re.split(r"(\[[^][]*])|[-+*/&,^%]", s)))
print(result)

Output

['[var1]', '[v/ar/2]', 'var3', 'var4']

Would you please try the following:

import re
formula = '[var1]+[v/ar/2]^var3/var4' #assume no spaces in the formula
m = re.findall(r'\[.+?\]|\w+', formula)
print(m)

Output:

['[var1]', '[v/ar/2]', 'var3', 'var4']

The regex \[.+?\]|\w+ matches either of:

  • anything surrounded with square brackets.
  • a sequence of non-special characters.

My solution (without any voodoo regex) is to split it into 3 steps:

  1. Get all the bracketed strings
  2. Remove all the bracketed strings from the formula
  3. Split on the remaining string
formula = '[var1]+[v/ar/2]^var3/var4'
out_list =re.findall('\[.*?\]',formula)
formula = re.sub('\[.*?\]','',formula)
out_list.extend([x for x in re.split('[-+*/&,^%]',formula) if x != ''])
Related