【问题标题】:How to extract content in between an opening and a closing bracket?如何在左括号和右括号之间提取内容?
【发布时间】:2022-02-19 01:12:03
【问题描述】:

我试图将一个字符串拆分为一个文本内容数组,每个文本内容都存在于[@ 和] 分隔符中。只允许匹配 [@ 和 ] 之间的字符。提供了一个类似 ...

的字符串
const stringA = '[@Mary James], [@Jennifer John] and [@Johnny Lever[@Patricia Robert] are present in the meeting and [@Jerry[@Jeffery Roger] is absent.'

...预期结果如下...

[
  'Mary James',
  'Jennifer John',
  'Patricia Robert',
  'Jeffery Roger'
]

可以使用任何导致预期结果的逻辑。

对解决方案的自我搜索提出了以下应用的正则表达式 ...

stringA.match(/(?<=\[@)[^\]]*(?=\])/g);

但结果不符合要求,因为数组包含以下项...

[
  'Mary James',
  'Jennifer John',
  'Johnny Lever[@Patricia Robert',
  'Jerry[@Jeffery Roger'
]

【问题讨论】:

  • 为什么不能满足您的要求?出了什么问题?
  • /\[@(?&lt;content&gt;[^\[\]]+)\]/g ... [ ...'[@Mary James], [@Jennifer John] and [@Johnny Lever[@Patricia Robert] are present in the meeting and [@Jerry[@Jeffery Roger] is absent.'.matchAll(/\[@(?&lt;content&gt;[^\[\]]+)\]/g) ].map(({ groups: { content } }) =&gt; content);
  • @JustinMorgan ... OP 的正则表达式在字符类中没有左括号,因此将 OP 的 /(?&lt;=\[@)[^\]]*(?=\])/g 更改为 (?&lt;=\[@)[^\[\]]*(?=\]) 已经解决了 OP 对于大多数环境(不包括 safari 浏览器)的问题由于不支持向后看。

标签: javascript regex match lookbehind capture-group


【解决方案1】:

OP 的正则表达式在否定字符类中没有左括号,因此将 OP 的 /(?&lt;=\[@)[^\]]*(?=\])/g 更改为 (?&lt;=\[@)[^\[\]]*(?=\]) 已经解决了 OP 在大多数环境中的问题 not including safari browsers due to the lookbehind which is not supported。

基于正则表达式的解决方案 .../\[@(?&lt;content&gt;[^\[\]]+)\]/g ... 和 named capture group ...

const sampleText = '[@Mary James], [@Jennifer John] and [@Johnny Lever[@Patricia Robert] are present in the meeting and [@Jerry[@Jeffery Roger] is absent.'

// see ... [https://regex101.com/r/v234aT/1]
const regXCapture = /\[@(?<content>[^\[\]]+)\]/g;

console.log(
  Array.from(
    sampleText.matchAll(regXCapture)
  ).map(
    ({ groups: { content } }) => content
  )
);

【讨论】:

    【解决方案2】:

    关闭,只是缺少[的排除:

    stringA.match(/(?<=\[@)[^\[\]]*(?=\])/g);
    //                       ^^ exclude '[' as well as ']'
    

    【讨论】:

    • ...查看我对不支持正则表达式的 safari 浏览器的评论 lookbehind
    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 2019-02-03
    • 2013-08-15
    • 2019-02-07
    • 1970-01-01
    • 2021-10-22
    • 2010-09-27
    • 2016-08-26
    相关资源
    最近更新 更多