Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to match inverse using negative lookahead ignores matches

I am trying to create a regex to match any tags not including [first].

# Trying to match:
# [second]
# [first.second]
# [first.third]

[first]
# something = else
[second]
test = yes
[first.second]
[first.third]

I was trying ^\[((?!first).*)\]$

https://regex101.com/r/1fz1CW/1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And this seems to match [second] in the example above but I can’t figure out why it doesn’t match [first.second] or [first.third] I was thinking I may need word boundaries, but I can’t seem to get them to work.

>Solution :

Use

^\[((?!first\])[^\]\[]*)\]$

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  \[                       '['
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
      first                    'first'
--------------------------------------------------------------------------------
      \]                       ']'
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
    [^\]\[]*                 any character except: '\]', '\[' (0 or
                             more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \]                       ']'
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading