[英]In JavaScript, how to split the string “aa,bb\\,cc,dd” by comma but only when the previous character is not backslash?
我有一个字符串aa,bb\\\\,cc,dd
。 我需要用逗号分隔它,但仅当前一个字符不是反斜杠时才可以。 所以我想要的是:
aa
bb\\,cc
dd
由于JavaScript正则表达式不支持负向回溯,因此我想知道在这种情况下如何解决它。 谢谢。
您可以将此正则表达式用于match
:
/(?=.)([^,\\]*(?:\\.[^,\\]*)*)(?:,|$)/gm
此正则表达式将忽略所有转义字符,同时匹配在下一个位置具有逗号或行尾的子字符串。
正则表达式详细信息:
(?=.)
:确保我们不匹配空字符串 ([^,\\\\]*
:匹配0个或多个不是char的字符,
和\\
(?:\\\\.[^,\\\\]*)*)
:匹配\\
后跟转义字符,然后匹配0或更多不是char的字符,
以及\\
。 (?:,|$)
:匹配逗号或行尾 const regex = /(?=.)([^,\\\\]*(?:\\\\.[^,\\\\]*)*)(?:,|$)/gm; const str = `aa,bb\\\\,cc,dd`; let m; while ((m = regex.exec(str)) !== null) { console.log(m[1]); } //=> [aa, bb\\,cc, dd]
如果要用逗号在后向断言中进行拆分,则可以按所有逗号进行拆分,然后在累积数组时在.reduce()
强制执行后在断言。
const str = 'aa,bb\\\\,cc,dd' const values = str.split(/,/g).reduce((acc, str) => { const lastIndex = acc.length - 1 if (lastIndex >= 0 && acc[lastIndex].endsWith('\\\\')) { acc[lastIndex] += str } else { acc.push(str) } return acc }, []) console.log(values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.