匹配模式后任何内容的正则表达式

Regex that matches whatever comes after a pattern

重要提示:我已经在 Whosebug 和其他地方查找过类似的问题,但找不到解决方案。

我正在尝试创建一个正则表达式来匹配此模式之后的任何内容(不包括模式本身)

[-a-zA-Z0-9]+\/[-\._a-zA-Z0-9]+

我尝试使用 ^ 作为 NOT 运算符,如下所示:

[^([-a-zA-Z0-9]+\/[-\._a-zA-Z0-9]+)]

但它抛出一个语法错误:Unmatched '('。似乎它将第一个 ] 与第一个 [ 而不是第二个相关联。如何解决这个问题?

我也试过像这样做一个积极的回顾:

(?<=([-a-zA-Z0-9]+\/[-\._a-zA-Z0-9]+).*)

但是没用。

我做错了什么?

const pattern = new RegExp('([-a-zA-Z0-9]+\/[-\._a-zA-Z0-9]+)([\/\?].*)');

if(pattern.test('hello/w0rld/blbalba0')){
  console.log('Matches string 1');
}


if(pattern.test('hel-lo/wor_ld?q=0')){
  console.log('Matches string 2');
}

// Invalid string
if(pattern.test('hello/w0rld)/blbalba0')){
  console.log('Matches string 3');
}

// Invalid string
if(pattern.test('hel-lo/wor_&ld?q=0')){
  console.log('Matches string 4');
}

// if you wish to access the matches
const matches = pattern.exec('hel-lo/wor_ld?q=0');
console.log(matches[2]);

Playground

您可以捕获第 1 组中匹配项之后的所有内容,并在替换中使用第 1 组。

[-a-zA-Z0-9]+\/[-._a-zA-Z0-9]+(.+)

要测试的文件内容:

hello/w0rld/blbalba0
hel-lo/wor_ld?q=0
hello/w0rld)/blbalba0
hel-lo/wor_&ld?q=0(

正如你在评论中提到的,你想使用 sed:

sed -E 's/[-a-zA-Z0-9]+\/[-._a-zA-Z0-9]+(.+)//' file

输出:

/blbalba0
?q=0
)/blbalba0
&ld?q=0(