Skip to content Skip to sidebar Skip to footer

Regex To Match All Words But AND, OR And NOT

In my javascript app I have this random string: büert AND NOT 3454jhadf üasdfsdf OR technüology AND (bar OR bas) and i would like to match all words special chars and numbers be

Solution 1:

The issue here has its roots in the fact that \b (and \w, and other shorthand classes) are not Unicode-aware in JavaScript.

Now, there are 2 ways to achieve what you want.

1. SPLIT WITH PATTERN(S) YOU WANT TO DISCARD

var re = /\s*\b(?:AND|OR|NOT)\b\s*|[()]/;
var s = "büert AND NOT 3454jhadf üasdfsdf OR technüology AND (bar OR bas)";
var res = s.split(re).filter(Boolean);
document.body.innerHTML += JSON.stringify(res, 0, 4);
// = > [ "büert", "3454jhadf üasdfsdf", "technüology", "bar", "bas" ]

Note the use of a non-capturing group (?:...) so as not to include the unwanted words into the resulting array. Also, you need to add all punctuation and other unwanted characters to the character class.

2. MATCH USING CUSTOM BOUNDARIES

You can use groupings with anchors/reverse negated character class in a regex like this:

(^|[^\u00C0-\u017F\w])(?!(?:AND|OR|NOT)(?=[^\u00C0-\u017F\w]|$))([\u00C0-\u017F\w]+)(?=[^\u00C0-\u017F\w]|$)

The capure group 2 will hold the values you need.

See regex demo

JS code demo:

var re = /(^|[^\u00C0-\u017F\w])(?!(?:AND|OR|NOT)(?=[^\u00C0-\u017F\w]|$))([\u00C0-\u017F\w]+)(?=[^\u00C0-\u017F\w]|$)/gi; 
var str = 'büert AND NOT 3454jhadf üasdfsdf OR technüology AND (bar OR bas)';
var m;
var arr = []; 
while ((m = re.exec(str)) !== null) {
  arr.push(m[2]);
}
document.body.innerHTML += JSON.stringify(arr);

or with a block to build the regex dynamically:

var bndry = "[^\\u00C0-\\u017F\\w]";
var re = RegExp("(^|" + bndry + ")" +                   // starting boundary
           "(?!(?:AND|OR|NOT)(?=" + bndry + "|$))" +    // restriction
           "([\\u00C0-\\u017F\\w]+)" +                  // match and capture our string
           "(?=" + bndry + "|$)"                        // set trailing boundary
           , "g"); 
var str = 'büert AND NOT 3454jhadf üasdfsdf OR technüology AND (bar OR bas)';
var m, arr = []; 
while ((m = re.exec(str)) !== null) {
  arr.push(m[2]);
}
document.body.innerHTML += JSON.stringify(arr);

Explanation:

  • (^|[^\u00C0-\u017F\w]) - our custom boundary (match a string start with ^ or any character outside the [\u00C0-\u017F\w] range)
  • (?!(?:AND|OR|NOT)(?=[^\u00C0-\u017F\w]|$)) - a restriction on the match: the match is failed if there are AND or OR or NOT followed by string end or characters other than those in the \u00C0-\u017F range or non-word character
  • ([\u00C0-\u017F\w]+) - match word characters ([a-zA-Z0-9_]) or those from the \u00C0-\u017F range
  • (?=[^\u00C0-\u017F\w]|$) - the trailing boundary, either string end ($) or characters other than those in the \u00C0-\u017F range or non-word character.

Post a Comment for "Regex To Match All Words But AND, OR And NOT"