Skip to content Skip to sidebar Skip to footer

Javascript Regex Negative Look-behind

I'm trying to figure out the correct regex to do this in javascript. In pcre, this does exactly what I want: /^.*(?

Solution 1:

Use the following regex to match the right text:

/(?:^|[^\/])kb([0-9]+)/i

See the regex demo

Details:

  • (?:^|[^\/]) - start of string or a char other than /
  • kb - a literal string kb
  • ([0-9]+) - Group 1 matching 1 or more digits.

var ss = ["If I have a value that isn't prefixed with a forward-slash, e.g KB12345, it'll match the number within.","If that value is prefixed with a forward-slash it won't match, e.g: http://someurl.com/info/KB12345"];
var rx = /(?:^|[^\/])kb([0-9]+)/i;
for (var s of ss) {
 var m = s.match(rx);
 if (m) { console.log(m[1], "found in '"+s+"'") };
}

Solution 2:

try this

a = /^(?!\/KB)kb([0-9]+)$/i.test('KB12345')
b = /^(?!\/KB)kb([0-9]+)$/i.test('http://someurl.com/info/KB12345')
c = /^(?!\/KB)kb([0-9]+)$/i.test('/KB12345')

console.log(a);
console.log(b);
console.log(c);

Post a Comment for "Javascript Regex Negative Look-behind"