Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Exclude Word

I'm trying to replace all of the event handling functions whose name is either "eventHandler" or ends with "...EventHandler" to be encapsulated in a common event-handling function which does additional tasks before actually calling a event handler.

In short, I'm trying to do this (in sublime text editor) using the regular expression in find & replace:

loginEventHandler(args, callback) => processEventHandler(loginEventHandler, args, callback)

[ Find ]

(eventHandler|(?!processEventHandler)\w+EventHandler)((.*))

[ Replace ]

processEventHandler($1, $2)

This isn't working as expected. The find is also matching rocessEventHandler . How do I ignore matching the function if the function name is "processEventHandler"?

I tried solutions mentioned in the following questions, but didn't help.

Regular expression to match line that doesn't contain a word?

A regular expression to exclude a word/string

Here is the test result:

Regular Expression Test Result

like image 995
sunilkumarba Avatar asked Jul 13 '26 21:07

sunilkumarba


1 Answers

Basically, your regex matches a part of the string with process is because the regex is not anchored at the start. If you need to match the strings at the start of a string, use ^. If you plan to just match them inside a larger text, use \b (word boundary).

You can use a regex with a negative lookahead anchored at the leading word boundary:

(?i)(\b(?!process)\w*EventHandler)\(([^)]*)\)

See regex demo

The regex (case-insensitive because of (?i) inline modifier) matches:

  • \b - a word boundary
  • (?!process) - a negative lookahead that fails a match if the following character sequence is found: \w* - zero or more alphanumeric symbols + EventHandler
  • \( - opening parenthesis
  • ([^)]*) - zero or more characters other than )
  • \) - closing parenthesis
like image 114
Wiktor Stribiżew Avatar answered Jul 16 '26 10:07

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!