Javascript Regex to find a word started with or followed by anything other than a character or digit

Viewed 50

I'm trying to find names of programming languages in text, I've tried for days to find the correct regex, but I can't find it. Also running into problems when the language is C++ or C# I want to match the name of the languages if it starts with or ends with anything other than letters or digits.

  reg = new RegExp("\\b[\\+" + language[element] + "] \\b", "gi");
1 Answers

You can use

new RegExp("(?<!\\w)" + language[element].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "(?!\\w|\\+{2}|#)", "gi");

See the regex demo if language[element] holds the C text. Details:

  • (?<!\w) - no word char allowed immediately before the current location
  • C - a C char
  • (?!\w|\+\+|#) - a negative lookahead that fails the match if there is a word char, or ++ or a # char immediately to the right of the current location.
Related