-3

I've found multiple posts with negative lookaheads, but I can't seem to make it work for this particular use case.

I have multiple lines with one of the following 4 patterns (and possibly more than 2 options):

text [option1/option2] text
text] [option1/option2] more text
text [option1/option2] [text
text] [option1/option2] [text

Looking for a regex (more likely multiple: one for left and one for right) that will match only the single-bracketed text (in bold below):

text [option1/option2] text

text] [option1/option2] more text

text [option1/option2] [text

text] [option1/option2] [text

Making multiple passes over the lines is fine. Also, this is Python, so if there's a completely different way, I'm open to suggestions. This are just strings in a list.

Thanks in advance -mS

Spitzer
  • 7
  • 2

3 Answers3

0

It looks like you're trying to match this.
What do you need with the look around assertions though ?

(text\] (?:\[option1/option2\])(?: \[text)?|(?:\[option1/option2\]) \[text)

=

 (
      text \] [ ]
      (?: \[ option1/option2 \] )
      (?: [ ] \[ text )?
   |  (?: \[ option1/option2 \] )
      [ ] \[ text
 )

see https://regex101.com/r/HxY4Uv/1


You can wrap capture groups around the 3 forms to see which matched
so you don't have to post process string's.

(text\]) (?:\[option1/option2\]) (\[text)?|(?:\[option1/option2\]) (\[text)

see https://regex101.com/r/CqzZID/1

0

following regex will match your lines as you want:

(^[^\[\]]*?\])|(\[(?!.*?\]).*)

Regex Demo

also (^[^\[\]]*?\])|(\[[^\[\]]*$) must work for which is without using look forward and simpler. you can split regex to (^[^\[\]]*?\]) and (\[[^\[\]]*$) ,then match each one against line to use matching group.

mjrezaee
  • 1,040
  • 2
  • 9
  • Nailed it with this one. This is perfect. I need to go through it to see what it's doing, but works great. Thank you. – Spitzer Jul 14 '20 at 17:53
0

Try this: (^\w+\])|(\[\w+$)

(^\w*\]) - match \w one and unlimited times ^ at start of a line followed by \].

| - OR

(\[\w+$) - match \w one and unlimited times preceded by \[ at the end of a line $.

demo

scicyb
  • 620
  • 3
  • 12