Home > Blockchain >  Regex to match inverse using negative lookahead ignores matches
Regex to match inverse using negative lookahead ignores matches

Time:01-10

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

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.

CodePudding user response:

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
  •  Tags:  
  • Related