Home > OS >  Exact match multiple words in regex (datatables)
Exact match multiple words in regex (datatables)

Time:12-20

I'm trying to create a regex search in Datatables which matches a user who belongs to all selected groups.

Example:

User A belongs to Users, Other, Other Users

User B belongs to Users, Other

If Users and Other Users are selected as filters, only user A should show in the table. The problem I'm having is that both users are showing when these filters are selected. I don't think the regex is matching exact strings and, after looking through multiple other answers, I don't seem to be able to get it to do so.

My solution:

if (!this.items.length) {
    table.column(i).search('');
} else {
    let regex = '^';

    this.items.forEach(v => regex  = `(?=.*\\b${v}\\b)`);

    regex  = '.*$'

    table.column(i).search(regex, true, false, true)
}

Which results in: ^(?=.*\bUsers\b)(?=.*\bOther Users\b).*$

However, the user belonging to Users,Other is still being returned.

CodePudding user response:

You can enforce a comma or start/end of string check before and after each of your search term:

this.items.forEach(v => regex  = "(?=.*(?:[^,]|^)${v}(?![^,]))");

Or, if the JavaScript environment supports lookbehinds:

this.items.forEach(v => regex  = "(?=.*(?<![^,])${v}(?![^,]))");

The (?:[^,]|^) / (?<![^,]) (equal to (?<=,|^)) part requires start of string position or a comma right before your search term and the (?![^,]) negative lookahead requires a comma or end of string immediately to the right of the current position ((?![^,]) is equal to (?=,|$) positive lookahead).

  • Related