【问题标题】:How to extract the strings within brackets using lookbehind and lookahead zero-length assertions?如何使用lookbehind和lookahead零长度断言提取括号内的字符串?
【发布时间】:2018-03-03 04:11:30
【问题描述】:

我想从"string[0][inner_string]"中提取0inner_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】:

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

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

    str = 'string[0][inner_string]'
    re = /\[([^\]]+)\]/g
    
    while(match = re.exec(str)) {
      console.log(match[1])
    }

    【讨论】:

    • 感谢您提供这些链接。我没有意识到 Chrome 正在工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2021-09-02
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多