Smally
Smally

Reputation: 1684

Greedy negative lookbehind (in Swift)

I'm in need of a regular expression that acts like the following:

matches (any part of foo() in the following statement):

does not match:

I currently have the following, but it has some problems:

^\s*?(?<!@)((\w+?)\()

If there's no ^\s*? in the regex, it would be behaving partly correct, but this shouldn't happen. It should rather discard the match entirely (not just for one character):

wrongly matched regex

It has to discard the match entirely if any @ is before it, although it must match this correctly: @Mode foo() (the foo() bit, disregarding the @Mode before it).

If there are any tips to help me out, that would be awesome!

Upvotes: 1

Views: 808

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18641

Use

(?<![\w@])\w+\(\)

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    [\w@]                    any character of: word characters (a-z,
                             A-Z, 0-9, _), '@'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \(                       '('
--------------------------------------------------------------------------------
  \)                       ')'

Upvotes: 1

Related Questions