[英]regex to split string by single char string but recognizing pairs of brackets and quotes
我正在尋找一種將字符串拆分為特定字符的方法,但考慮到一些基本語法,本質上是檢測匹配的方括號和引號對並將它們視為一個單元。 我不確定使用regexp是否可行,至少對於我的專業水平而言不是。
let str="a,pow(3,4),new Value({a:1,b:2}),'{this is a literal, all (this) is a \"single entity'";
let regexp=/what goes here?/;
let arr=str.split(regexp);
預期結果:
我希望它不是重復的,無法找到以前的答復
不幸的是, (*SKIP)(*FAIL)
在JS
不受支持,但是您可以稍微模仿一下:
\\([^()]*\\)|'[^']*'|(,)
...以及JavaScript
代碼:
var subject = "a,pow(3,4),new Value({a:1,b:2}),'{this is a literal, all (this) is a \\"single entity'"; var regex = /\\([^()]*\\)|'[^']*'|(,)/g; replaced = subject.replace(regex, function(m, group1) { if (typeof group1 == 'undefined') return m; else return "SUPERMAN"; }); console.log(replaced.split(/SUPERMAN/));
PCRE
(?:(\\((?:[^()]*|(?1))*\\))|'[^']*')(*SKIP)(*FAIL)|,
這也支持嵌套括號,請參見regex101.com上的演示 。
否則,您需要在此處編寫一個小型解析器。
您正在標記字符串,因此,您可以匹配1個或多個'...'
, (...)
子字符串或除逗號以外的任何1+個字符的塊。
采用
/(?:'[^']*'|\([^()]*\)|[^,])+/g
這是正則表達式演示 。
細節
(?:'[^']*'|\\([^()]*\\)|[^,])+
-1個或多個序列:
'[^']*'
-a '
, '
和'
以外'
0+個字符 |
- 要么 \\([^()]*\\)
-a (
char,除(
和)
0+個字符,然后是)
|
- 要么 [^,]
-除以外的其他字符,
參見JS演示:
let str="a,pow(3,4),new Value({a:1,b:2}),'{this is a literal, all (this) is a \\"single entity'"; let rx = /(?:'[^']*'|\\([^()]*\\)|[^,])+/g; console.log(str.match(rx));
嵌套括號的方法:
function splitIt(str) { var result = [], start = 0, level = 0, in_par = false, in_quotes = false; for (var i = 0; i < str.length; ++i) { switch (str[i]) { case '(': if (!in_quotes) ++level; break; case ')': if (level > 0 && !in_quotes) --level; break; case "'": in_quotes = !in_quotes; break; case ',': if (level || in_quotes || in_par) break; if (start < i) { result.push(str.substr(start, i - start)); } start = i + 1; break; } } if (start < i) result.push(str.substr(start, i - start)); return result; } var s = "a,pow(3,(4,5)),new Value({a:1,b:2}),'{this is a literal, all (this) is a \\"single entity'"; console.log(splitIt(s))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.