【发布时间】:2019-06-20 15:59:41
【问题描述】:
我正在尝试string.matchAll以下字符串:
const text = 'textA [aaa](bbb) textB [ccc](ddd) textC'
我想匹配以下内容:
- 第一:
"textA [aaa](bbb)" - 第二:
" textB [ccc](ddd)" - 第三:
" textC"
注意: 捕获组已经存在于regex 中。这就是我需要的。
它几乎可以工作,但到目前为止我想不出一种方法来匹配字符串的最后一部分,即" textC",并且没有[*](*) 模式。
我做错了什么?
const text = 'textA [aaa](bbb) textB [ccc](ddd) textC'
const regexp = /(.*?)\[(.+?)\]\((.+?)\)/g;
const array = Array.from(text.matchAll(regexp));
console.log(JSON.stringify(array[0][0]));
console.log(JSON.stringify(array[1][0]));
console.log(JSON.stringify(array[2][0]));
更新:
除了以下答案中提供的良好解决方案之外,这也是一种选择:
const text= 'textA [aaa](bbb) textB [ccc](ddd) textC'
const regexp = /(?!$)([^[]*)(?:\[(.*?)\]\((.*?)\))?/gm;
const array = Array.from(text.matchAll(regexp));
console.log(array);
【问题讨论】:
-
试试这个:(\w+)\s*(?:[(.+?)]((.+?)))?
-
(.+\)) (.+\)) (.+)有什么问题吗? -
My answer 将用于拆分具有任何模式的任何字符串,同时将匹配的文本保留在左侧拆分块中。它对你有用吗?您确定您需要的结果是您在问题中显示的结果吗?
textC是占位符吗,它可以等于word 1 word 2 and word 3 and so on....并且您需要将此文本作为结果数组中的单个项目获取?
标签: javascript regex