Javascript regex negative look-behind

六月ゝ 毕业季﹏ 提交于 2019-12-10 22:38:42

问题


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

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



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


来源:https://stackoverflow.com/questions/45346875/javascript-regex-negative-look-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!