JS regex matching whole words with hyphen In dataTables

Not sure if this is best posted here or on the JQ dataTables forum. I'll try here.

Doing exact regex matching on columns in a dataTable and have two cases one works great but the second not so good!

CASE 1 Column data

Joe    
Bob    
Sue   
Bobby    
Joey

So then I want all the rows that have Joe, Bob, Sue and not Bobby and Joey.

MY regex looks like this;

 \b(Joe|Bob|Sue)\b

And it works great. I see filtered rows for the three names and not Bobby and Joey. I use the pipe separated list because I also store the filter list in URL parameter so the filtered version can be book marked.

Now my problem case: CASE 2 Column data

Joe    
Bob    
Sue   
Bobby    
Joey
Ann
Jo-Ann

In this case I want Bob Sue and Ann rows.

Using this regex

\b(Bob|Sue|Ann)\b

Gets the rows I want but also gets the Jo-Ann Rows, I assume because the - is being treated as a boundary between words.

Play around with [\w-] but can't seem to get it work on a pipe separated list. Below is the fiddle.

http://refiddle.com/1v1j

Thanks,

Dave

Answers:

Answer

You could create a DIY boundary.

Using either a capture or non-capturing group we can assert that the start of the string or a space character precedes while asserting that a space character or the end of the string follows your grouped pattern.

(?:^| )(Bob|Sue|Ann)(?: |$)

You could also use a negated character class if you prefer. On the right side of the alternation operator, instead of matching a space character in the above regular expression, we match a character that is not a hyphen or a word character, which is closer to the intent of expanding the word boundary and do the same for the group that follows.

(?:^|[^-\w])(Bob|Sue|Ann)(?:[^-\w]|$)
Answer

line feed could be applied in your case

/\s*(Bob|Joe|Ann)\s*\n/g
Answer
^(?:Bob|Sue|Ann)$

You can apply anchors as well.See demo.

https://www.regex101.com/r/fG5pZ8/3

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.