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
JavaScript
x
6
1
import re
2
line = "[ choice A | choice B ] and choose between [ choice D | choice F ]"
3
x = re.findall( r"[(.*?)|", line)[0].strip()
4
line = re.sub(r"[(.*?)]", x,line)
5
print(line)
6
Advertisement
Answer
You can use
JavaScript
1
5
1
import re
2
line = "[ choice A | choice B ] and choose between [ choice D | choice F ]"
3
line = re.sub(r"[s*([^][|]*?)s*|[^][]*]", r"1", line)
4
print(line) # => choice A and choose between choice D
5
See the Python demo and the regex demo. The regex matches
[
– a[
chars*
– 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 possibles*|
– zero or more whitespaces and a|
char[^][]*
– any zero or more chars other than]
and[
]
– a]
char.