Skip to content
Advertisement

Regex to keep one choice in square bracket

I am trying to write a regex to replace the whole square bracket with the first choice. For example, [ choice A | choice B ] I want to replace the previous square bracket as a whole with choice A. However, when I have more than one of these brackets:

[ choice A | choice B ] and choose between [ choice D | choice F ]

in the same line, all the brackets get replaced by choice A. I know it’s because I am selecting [0] in my code, but I don’t know how to replace each bracket with its respective choice; namely, choice A and choice D

import re
line = "[ choice A | choice B ] and choose between [ choice D | choice F ]"
x = re.findall( r"[(.*?)|", line)[0].strip()
line = re.sub(r"[(.*?)]", x,line)
print(line)

Advertisement

Answer

You can use

import re
line = "[ choice A | choice B ] and choose between [ choice D | choice F ]"
line = re.sub(r"[s*([^][|]*?)s*|[^][]*]", r"1", line)
print(line) # => choice A and choose between choice D

See the Python demo and the regex demo. The regex matches

  • [ – a [ char
  • s* – zero or more whitespaces
  • ([^][|]*?) – Group 1 (1 in the replacement pattern refers to this value): zero or more chars other than [, ] and |, as few as possible
  • s*| – zero or more whitespaces and a | char
  • [^][]* – any zero or more chars other than ] and [
  • ] – a ] char.
Advertisement