Home > Enterprise >  Regex that only matches with the given positive number and does not match with the negative number
Regex that only matches with the given positive number and does not match with the negative number

Time:08-28

Sample string: const str = "1 1 2 -2 5 2 4 4 -1 -2 5"

When I do str.match(/1/g) the result is ['1', '1', '1'] which is expected because "... -1 ..." is also getting a match.

The desire is to have a regex str.match(regex) that will only return ['1', '1'].

Ideally the desired regex will be declared like so: let regex = new RegExp(e, "g") where e could be any integer.

CodePudding user response:

Match 1 with a non - before it. Or a beginning of sentence. Thanks to @Lucas Sanchez for the Negative Lookbehind (?<!) Assert that the Regex does not match

const str = "1 1 2 -2 5 2 4 4 -1 -2 5"
var digit = 1;
var reg = new RegExp("(?<!\\S)"   digit   "|^("   digit   ")", "g");
console.log(str.match(reg))

CodePudding user response:

This should do the trick. It uses a negative lookahead and negative lookbehind that looks for non white space characters.

(?<!\S)1(?!\S)

const string = '1 1 2 -2 5 2 4 4 -1 -2 5 1 11 -2 -1';
const regex = /(?<!\S)1(?!\S)/g;
console.log(string.match(regex));

CodePudding user response:

Using javascript string template literals for a more readable code :

const str = "1 1 2 -2 5 2 4 4 -1 -2 5"
const digit = 5;
const reg = new RegExp(`(?<!\\S)${digit}|^(${digit})`, "g");
console.log(str.match(reg))

Output

[LOG]: ["5", "5"] 
  • Related