Reputation: 127
I'm trying to figure out how to write the correct regex so when jquery DataTables searches one column it finds exact matches. I have values of C-, C+, C and if someone clicks "C" I need it to only grab exact matches of C and not the other 2.
If they choose C- and C it should grab all entries with either of those 2, but C+ shouldn't be included.
I tried regex of: "C-|C+" but it grabs all C as well.
Here's the code I have creating that regex:
$("input[name='tourneyLevel']").on("change", function(e) {
var levelSelected = [];
$("input[name='tourneyLevel']:checked").each(function(index, city) {
levelSelected.push([$(this).val()]);
});
var regex = levelSelected.join("|");
console.log(regex);
$('.dataTable').DataTable().column(4).search(regex, true, false).draw();
});
Upvotes: 2
Views: 2046
Reputation: 709
"+" and "-" tend to have special meaning in RegEx. When constructing your RegEx try to escape them and put the phrases in a group, as you want to match the complete group.
So your user is searching for "C+"?
(C\+)
Your user is searching for "C" or "C-"?
(C\-)|(C)
Your user is searching for "C-" or "C+"?
(C\-)|(C\+)
Your user is searching for any of the three possibilities?
(C\-)|(C)|(C\+)
The plus sign normally means "one or more of the previous group". A minus is often used in ranges or to exclude stuff. Be careful when searching for these special characters. And when searching for multiple characters in a specific order you should try to group them with parentheses.
Furthermore the backslash is used to escape characters in a string. When constructing a RegEx by concatenating strings you have to escape the backslash with a second backslash so that the resulting RegEx contains a single backslash. This may sound complicated, but it boils down to:
Use two backslashes to escape a character in your RegEx when you are constructing the RegEx by concatenating strings.
To make sure that only this specific sequence is matched you can use two more important special characters:
^
for the start$
for the endFor example you can use the RegEx (^C$)
to only match exactly a single "C". The sequence starts, contains exactly the character "C" and ends when using this RegEx.
Upvotes: 4