Match any character except '

1.3k views Asked by At

I want to match any character (case insensitive) except when preceded by a single quote followed by the text On Error Goto:

Match:

on error goto err_handler
if aap = 0 then on error goto Myerrorhandler
    on error goto errorhandler1
   on error goto errorhandler2

Do not match:

' on error goto errorhandler3
'   if aap =0 then on error goto errorhandler4
Any line not containing On Error Goto

I tried: [^']*(On Error Goto) but that didn't work.

It is to test if an Errorhandler is used in procedures

Thanks!

2

There are 2 answers

1
Ryszard Czech On BEST ANSWER

Use

^[^'\n\r]*On Error Goto

Use i case insensitive mode and m multiline mode. See proof.

Explanation

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [^'\n\r]*                any character except: ''', '\n' (newline),
                           '\r' (carriage return) (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  On Error Goto            'On Error Goto'
0
nvkrj On

Updated link to regex test cases: https://regex101.com/r/UYll0h/6

Since there can be no character when ' isn't there, therefore you will need to use a look-ahead assertion.

Since there can also be other characters of the code (other than ') in the line before on error goto (like in the line if aap = 0 then on error goto Myerrorhandler), to handle those, you will also need to put a condition to check if any character other than ' is present after the look-ahead. This will be done by ([^']+)?.

^(?!')([^']+)?on error goto

The (?) is called a look-ahead. It checks if the characters inside it are present or not. Unlike [], (?) will assert true even when there are no characters. So for example, [a] will check if the first character is 'a', but any expression after it will check from the second character. On the other hand, (?=a) will check if the first character is 'a', and any expression after it will check from the first character. In other words, the look-ahead doesn't move the regex engine to the next character if a match is not found.