JS正则表达式匹配整个单词与连字符在dataTables [英] JS regex matching whole words with hyphen In dataTables
问题描述
不知道这是否最好在这里或JQ dataTables论坛上发布。我会在这里尝试。
Not sure if this is best posted here or on the JQ dataTables forum. I'll try here.
对dataTable中的列进行精确的正则表达式匹配,有两种情况下,一个非常好,但第二个不太好!
Doing exact regex matching on columns in a dataTable and have two cases one works great but the second not so good!
CASE 1
列数据
Joe
Bob
Sue
Bobby
Joey
那么那么我想要所有的行有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
它的效果很好。我看到三个名称的过滤行,而不是Bobby和Joey。
我使用管道分隔列表,因为我也将过滤器列表存储在URL参数中,所以过滤的版本可以被书签。
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.
现在我的问题案例:
CASE 2
列数据
Now my problem case: CASE 2 Column data
Joe
Bob
Sue
Bobby
Joey
Ann
Jo-Ann
在这种情况下,我想要Bob Sue和Ann行。
In this case I want Bob Sue and Ann rows.
使用这个正则表达式
\b(Bob|Sue|Ann)\b
获取我想要的行还会得到Jo-Ann Rows,我认为是因为 - 被视为单词之间的边界。
Gets the rows I want but also gets the Jo-Ann Rows, I assume because the - is being treated as a boundary between words.
播放[\w- ]但似乎无法使其在管道分隔列表上工作。
以下是小提琴。
Play around with [\w-] but can't seem to get it work on a pipe separated list. Below is the fiddle.
谢谢,
Dave
推荐答案
您可以创建一个 DIY 边界。
使用捕获或非捕获组我们可以断言字符串或空格字符的开头在声明空格字符或字符串末尾跟随您的分组模式之前。
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]|$)
这篇关于JS正则表达式匹配整个单词与连字符在dataTables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!