如何使用lookbehind和lookahead零长度断言提取括号内的字符串?

问题描述 投票:0回答:1

我想从0中提取inner_string"string[0][inner_string]"

我的方法使用lookbehind和looahead零长度断言。

这是正则表达式:

              +--- Look ahead
              |
              v
/(?<=\[)(.*?)(?=\])/g
  ^
  |
  +--- Look behind

var str = "string[0][inner_string]";
console.log(str.match(/(?<=\[)(.*?)(?=\])/g));

但是,我收到了一个错误。

是否可以使用环视?

javascript regex lookahead lookbehind
1个回答
1
投票

引用@ctwheels:“Lookbehinds在JavaScript(see the current stage of the TC39 proposal)中几乎没有支持。在撰写本文时,只有Chrome(从版本62开始)和Moddable(在2018年1月17日之后)支持JavaScript中的外观。”

正则表达式:\[([^\]]+)\]

str = 'string[0][inner_string]'
re = /\[([^\]]+)\]/g

while(match = re.exec(str)) {
  console.log(match[1])
}
© www.soinside.com 2019 - 2024. All rights reserved.