让我们以这一行为例:
这是一个 [13125] 字符串,[9414] 它很长。 [123897] 它比平均 [73941] 长 [38153]。
如何匹配整行并对每次出现的 [number]
以及其间的所有内容进行分组?
到目前为止我有这个正则表达式:/(.*)(\[\d*\])(.*)/
。它按预期工作,但仅对最后一次出现的 [number]
进行分组。我希望它做这样的事情:
Group 1: This is a
Group 2: [13125]
Group 3: string and
Group 4: [9414]
...
最佳答案
你可以像这样使用正则表达式
const str = "This is a [13125] string and [9414] it's long. [123897] it's longer [38153] than an average [73941]";
// Match [number] OR everything before [number]
// globally with g flag
const m = str.match(/((\[\d+\])|(.*?)(?=\[\d+\]))/g);
console.log(m)
关于javascript - 匹配整行,对序列中所有出现的地方以及中间的所有内容进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63588828/