Javascript 正则表达式否定回顾

Javascript regex negative look-behind

我正试图在 javascript 中找出正确的正则表达式来执行此操作。在 pcre 中,这正是我想要的:

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

目标:

然而,虽然它在 pcre 中有效,但在 javascript 中无效,因为否定句法:

(?<!\/)

我一直试图在 regex101 中解决这个问题,但还没有成功。关于 javascript 中的纯正则表达式等价物的任何想法或建议是什么?

我看到有负面的前瞻性,但我似乎无法弄清楚:

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

试试这个

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);

使用以下正则表达式匹配正确的文本:

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

regex demo

详情:

  • (?:^|[^\/]) - 字符串或 /
  • 以外的字符的开头
  • kb - 文字字符串 kb
  • ([0-9]+) - 第 1 组匹配 1 个或多个数字。

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+"'") };
}