Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

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 != ''])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...