如何提取左括号和右括号之间的内容?
How to extract content in between an opening and a closing bracket?
我试图将一个字符串拆分为一个文本内容数组,每个文本内容都存在于 [@
和 ]
分隔符中。只允许匹配 [@
和 ]
之间的字符。提供类似 ...
的字符串
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'
]
关闭,只是缺少 [
的排除:
stringA.match(/(?<=\[@)[^\[\]]*(?=\])/g);
// ^^ exclude '[' as well as ']'
OP 的正则表达式在否定字符 class 中没有左括号,因此将 OP 的 /(?<=\[@)[^\]]*(?=\])/g
更改为 (?<=\[@)[^\[\]]*(?=\])
已经解决了大多数环境下的 OP 问题 not including safari browsers due to the lookbehind which is not supported.
基于正则表达式的解决方案 ... /\[@(?<content>[^\[\]]+)\]/g
... with a 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
)
);
我试图将一个字符串拆分为一个文本内容数组,每个文本内容都存在于 [@
和 ]
分隔符中。只允许匹配 [@
和 ]
之间的字符。提供类似 ...
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'
]
关闭,只是缺少 [
的排除:
stringA.match(/(?<=\[@)[^\[\]]*(?=\])/g);
// ^^ exclude '[' as well as ']'
OP 的正则表达式在否定字符 class 中没有左括号,因此将 OP 的 /(?<=\[@)[^\]]*(?=\])/g
更改为 (?<=\[@)[^\[\]]*(?=\])
已经解决了大多数环境下的 OP 问题 not including safari browsers due to the lookbehind which is not supported.
基于正则表达式的解决方案 ... /\[@(?<content>[^\[\]]+)\]/g
... with a 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
)
);