[英]A RegEx to split by semicolon outside single or double quotes
I need a JavaScript RegEx to split a string by semicolon outside single or double quotes.我需要一个 JavaScript RegEx 在单引号或双引号之外用分号拆分字符串。
Actually i'm using the following regex /(?;\B['"][^'"]*)?(?![^'"]*['"]\B)/gm
that sadly doesn't cover every case.实际上我正在使用以下正则表达式
/(?;\B['"][^'"]*)?(?![^'"]*['"]\B)/gm
遗憾地没有涵盖每一个案例。
What i need:我需要的:
const string = `Lorem ipsum; "dolor sit; amet"; consectetur 'adipiscing; elit.' Fusce; sit amet ligula.; Phasellus in laoreet quam.`;
const resultArr = string.split(/THEREGEX/gm);
console.log(resultArr);
// ["Lorem ipsum", "\"dolor sit; amet\"", " consectetur 'adipiscing; elit.' Fusce", "sit amet ligula.", " Phasellus in laoreet quam."]
You may use this regex:你可以使用这个正则表达式:
((?:[^;'"]*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*')[^;'"]*)+)|;
Code:代码:
const s = `Lorem ipsum; "dolor sit; amet"; consectetur 'adipiscing; elit.' Fusce; sit amet ligula.; Phasellus in laoreet quam.` const re = /((?:[^;'"]*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*')[^;'"]*)+)|;/ console.log( s.split(re).filter(Boolean) )
RegEx Details:正则表达式详细信息:
(
: Start capture group #1 (
: 开始捕获组 #1
[^;'"]*
: Match 0 or more any character that are not '
and "
and not ;
[^;'"]*
: 匹配 0 个或多个不是'
和"
而不是;
(?:
: Start non-capture group (?:
: 启动非捕获组
"(?:\\.|[^"])*"
: Match a double quoted substring ignoring all escaped quotes "(?:\\.|[^"])*"
:匹配双引号 substring 忽略所有转义引号|
: OR '(?:\\.|[^'])*'
: Match a single quoted substring ignoring all escaped quotes '(?:\\.|[^'])*'
:匹配单引号 substring 忽略所有转义引号)
: End non-capture group )
: 结束非捕获组[^;'"]*
: Match 0 or more any character that are not '
and "
and not ;
[^;'"]*
: 匹配 0 个或多个不是'
和"
而不是;
)
: End capture group #1 )
: 结束捕获组 #1|
: OR ;
: Match a ;
;
.filter(Boolean)
: is used to remove empty results from split array .filter(Boolean)
:用于从拆分数组中删除空结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.