2

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

/^.*(?<!\/)kb([0-9]+).*$/im

Goal:

  • 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

However it looks like while this works in pcre, it won't work in javascript due to the syntax of the negation:

(?<!\/)

I've been trying to figure this out in regex101 but no luck yet. Any ideas or suggestions on what the pure-regex equivalent in javascript is?

I saw there's a negative look-ahead, but I can't seem to figure it out:

/^.*(?!\/KB)kb([0-9]+).*$/im
Tiago
  • 1,984
  • 1
  • 21
  • 43

2 Answers2

4

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+"'") };
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
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);
ewwink
  • 18,382
  • 2
  • 44
  • 54