Javascript-Regex表达式,用于在分号上拆分字符串,除非在单引号或双引号内使用



我目前正在使用以下regex,但当我有未闭合的引号时,它会失败。

const expression = /([^;"']+(("((\")|[^"])*")|('((\')|[^'])*')|[^;'"]*)*);?/gm;
const matchedArray = str.match(expression);

所以这很好用:str;that;works;

这也是:str;that'works;';fine"always";

但这失败了:str'doesn't work';,因为它删除了最后一个单引号

这也失败了:str'doesn''t work';,因为它删除了最后一个单引号

因此,我需要一个正则表达式来支持我现有的字符串以及那些中断的字符串。非常感谢。

这个想法是在拆分之前隐藏带引号的字符串,然后恢复它们。逃避现实的引用不是引用;也不是转义分号,分号。未闭合的引号一直持续到字符串的末尾。

let hidden = [];

const split = str => str
.replace (/(?<!\)'([^']|\')*((?<!\)'|$)|(?<!\)"([^"]|\")*((?<!\)"|$)/g, s => 'x01' + hidden.push (s) + 'x02')
.split (/(?<!\);/)
.map (s => {
for (let i = 0; i < hidden.length; i++) {
s = s.replace ('x01' + (i + 1) + 'x02', hidden [i]);
}
return s;
});

const tests = [
`str;that'works;';fine"always";`,
`str'doesn't work';`,
`str'doesn't work';`,
`str'doesn\'t work';`,  
`str'doesn''t work';or does it?`,
`str'doesn\''t work';or does it?`  
];
for (let test of tests) {
console.log (test + ' => ' + split (test));
}

最新更新