【发布时间】:2023-03-30 05:44:02
【问题描述】:
已经有很多类似的问题,但在我的情况下它们都不起作用。我有一个在双引号内包含多个子字符串的字符串,这些子字符串可以包含转义的双引号。
例如对于字符串 ',然后,“这是一些带有引号和 \"转义引号\" 的示例文本”。并不是说我们需要更多,而是……“这是“另一个”。以防万一。',预期的结果是一个包含两个元素的数组;
"this is some sample text with quotes and \"escaped quotes\" inside""here is \"another\" one"
/"(?:\\"|[^"])*"/g 正则表达式在regex101 上按预期工作;但是,当我使用 String#match() 时,结果会有所不同。看看下面的sn-p:
let str = 'And then, "this is some sample text with quotes and \"escaped quotes\" inside". Not that we need more, but... "here is \"another\" one". Just in case.'
let regex = /"(?:\\"|[^"])*"/g
console.log(str.match(regex))
我得到了四个,而不是两个匹配,而且转义引号内的文本甚至不包括在内。
MDN mentions 表示如果使用g 标志,将返回所有匹配完整正则表达式的结果,但不会返回捕获组。如果我想获取捕获组并设置了全局标志,我需要使用RegExp.exec()。我试过了,结果是一样的:
let str = 'And then, "this is some sample text with quotes and \"escaped quotes\" inside". Not that we need more, but... "here is \"another\" one". Just in case.'
let regex = /"(?:\\"|[^"])*"/g
let temp
let matches = []
while (temp = regex.exec(str))
matches.push(temp[0])
console.log(matches)
我怎样才能得到一个包含这两个匹配元素的数组?
【问题讨论】:
标签: javascript regex regex-group string-matching