本文介绍了Javascript 正则表达式负向后视的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

目标:

  • 如果我有一个不带正斜杠前缀的值,例如 KB12345,它将匹配其中的数字.
  • 如果该值以正斜杠为前缀,它将不匹配,例如:http://someurl.com/info/KB12345
  • 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

然而,虽然它在 pcre 中有效,但由于否定的语法,它在 javascript 中不起作用:

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

(?<!\/)

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

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

推荐答案

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

Use the following regex to match the right text:

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

查看正则表达式演示

详情:

  • (?:^|[^\/]) - 字符串或 / 以外的字符的开头
  • kb - 文字字符串 kb
  • ([0-9]+) - 第 1 组匹配 1 个或多个数字.
  • (?:^|[^\/]) - 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+"'") };
}

这篇关于Javascript 正则表达式负向后视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 11:21