Javascript RegEx for matching words without leading or ending hyphens

I need RegEx for Javascript, which will match the line "blacksmith" in lines 1-4, but not in lines 5-8 below.
Numbered rows are fields in an Access database (fields do not contain numbers).
What I still have:

var xy = 'smith'; MyString = new RegExp('(^|\\W)' + xy + '(\\W|$)', 'i'); 

This corresponds to the Smiths in lines 1-4, but also in Line 7 and 8.
How can I make an expression also ignore Smiths preceded or followed by a hyphen?

  • Smith, Jones, Wilson
  • Smith Jones Wilson
  • Jones, Smith (Jr.), Wilson
  • Jones, Wilson, Smith
  • Arrowsmith, jones
  • Wilson, Smithson
  • Jones, Smith-Threadston, Wilson
  • Wilson, Blakely Smith, Jones

After a week and dozens of attempts, I ask experts!

+4
source share
1 answer

Enter the negative character class ( \W ) and include the hyphen:

 MyString = new RegExp('(^|[^a-z0-9_-])' + xy + '([^a-z0-9_-]|$)', 'i'); 

While \W matches any character without a word (everything except letters, numbers and underscores), [^a-z0-9_-] matches any character that is neither a word character nor a hyphen.

Of course, you can use \W in this character class:

 MyString = new RegExp('(^|[^\\w-])' + xy + '([^\\w-]|$)', 'i'); 
+3
source

Source: https://habr.com/ru/post/1442657/


All Articles