簡體   English   中英

正則表達式按單個字符字符串拆分字符串,但可以識別成對的括號和引號

[英]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);

預期結果:

  • 一種
  • 戰俘(3,4)
  • 新值({a:1,b:2})
  • '{這是文字,所有(this)都是\\“單個實體”

我希望它不是重復的,無法找到以前的答復

不幸的是, (*SKIP)(*FAIL)JS不受支持,但是您可以稍微模仿一下:

  1. 定義您希望匹配的內容並將其交替顯示。
  2. 定義您要匹配的內容並將其放入捕獲組
  3. 用sth代替組。 在原始字符串中不會出現
  4. 按此順序拆分。


表達方式

 \\([^()]*\\)|'[^']*'|(,) 

...以及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/)); 


在regex101.com上查看表達式演示,並閱讀@ctwheels的注釋-上面的代碼段不適用於遞歸子模式。
可以 (不是說, 應該 )用另一種支持遞歸模式的語言使用遞歸方法,例如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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM