I need a regex to search in visual studio code for words starting with a specific string followed by letters that vary but exclude 3 specific cases

Viewed 538

I need to search within my project, all words starting with the string "use" followed by any uppercase letter and other than these three cases:

  • useRef
  • useEffect
  • useState

Valid searches would be:

  • useExample
  • useTest
  • useWhatever

And invalid searches:

  • usefoo
  • usebar

In addition to the 3 strings mentioned above.

This is as far as I've managed to go, but in vscode it seems to have a different behavior than any regular expression checker and I don't really know where to go from here:

^(?!useRef)(use.*)
1 Answers

You can use the following regex:

\buse(?!(?:Ref|Effect|State)\b)[A-Z][a-zA-Z]*\b

See this regex demo.

Pattern details:

  • \b - a word boundary
  • use - a use string
  • (?!(?:Ref|Effect|State)\b) - a negative lookahead that fails the match if there is Ref, Effect or State substrings followed with a word boundary immediately to the right of the current location
  • [A-Z] - an uppercase ASCII letter
  • [a-zA-Z]* - any zero or more ASCII letters
  • \b - a word boundary.

Regex graph:

enter image description here

Related