简体   繁体   English

javascript regexp:匹配 :: 之后的所有内容,但不匹配 >

[英]javascript regexp: match everything after :: but not >

I created this regex: /[::].+[^\\>]/g我创建了这个正则表达式:/[ /[::].+[^\\>]/g

Test:测试:

 let str = "<foo::bar>" let match = str.match(/[::].+[^\\>]/g).join('') console.log(match)

Expected answer : bar预期答案: bar

Actual answer : ::bar实际答案::bar

Answers appreciated.答案表示赞赏。

One option is to use a lookbehind assertion ( (?<=) ), which is currently supported only by Chrome & Safari:一种选择是使用后视断言( (?<=) ),目前只有 Chrome 和 Safari 支持:

 const str = "<foo::bar>" const match = str.match(/(?<=::)[^\\>]+/g).join('') console.log(match)

Adding an extra match & join to remove '::' had solved the problem.添加一个额外的匹配和连接来删除 '::' 已经解决了这个问题。

Working code:工作代码:

let str = "<foo::bar>"
let match = str.match(/[::].+[^\>]/g).join('')
            .match(/[^(::)].+/g).join()
console.log(match)

Another option is to use a capturing group instead of a lookbehind:另一种选择是使用捕获组而不是后视:

::([^>]+)

Regex demo正则表达式演示

For example例如

 const regex = /::([^>]+)/g; const str = `<foo::bar>`; let m; let match = []; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } match.push(m[1]); } console.log(match.join(''));


If you want to match the whole pattern of the string, you might use:如果要匹配字符串的整个模式,可以使用:

<[^>]+::([^>]+)>

Regex demo正则表达式演示

 const regex = /<[^>]+::([^>]+)>/g; const str = `<foo::bar>`; let m; let match = []; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } match.push(m[1]); } console.log(match.join(''));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM