[英]Regex extract list of strings between two strings
我有一個字符串,我想從中提取包含在兩個字符串之間的字符串列表: ['
和']
。 我嘗試了幾個我在網上找到的正則表達式規則(特別是這個問題),但問題在於正確轉義字符以使正則表達式工作。
如何提取兩個字符串之間的字符串列表? 我想做這樣的事情:
List<string> TheListOfStrings = Regex.Matches(TheText, "....");
源是從欲提取對象鍵一個JavaScript塊:用於instrance, TheObject['SomeProp'] = TheOtherObject['OtherProp']
等的列表應包含SomeProp
和OtherProp
; 這些鍵可以在輸入文本中多次出現。
您唯一的主要困難是使方括號被識別為分隔文本而不是正則表達式的一部分。
string input = "a['bc']d['ef']gh']";
MatchCollection matches = Regex.Matches(input, @"\['(?<key>.*?)'\]");
var listOfKeys = matches.Cast<Match>().Select(x => x.Groups["key"].Value);
訣竅。
如果性能很重要並且它會運行多次,那么編譯正則表達式將看到明顯的勝利:
string input = "a['bc']d['ef']gh']";
Regex re = new Regex(@"\['(?<key>.*?)'\]", RegexOptions.Compiled);
MatchCollection matches = re.Matches(input);
var listOfKeys = matches.Cast<Match>().Select(x => x.Groups["key"].Value);
使用通用模式
(?<=prefix)find(?=suffix)
它使用lookbehind 和lookahead 來查找模式而不將它們包含在結果中。
在哪里
前綴是\\['
; 左括號被轉義。
發現是.*?
; 任何字符的序列,但盡可能少。
后綴是']
(?<=\[').*?(?='])
List<string> TheListOfStrings = Regex.Matches(input, @"(?<=\[').*?(?='])")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
如果您重復調用相同的正則表達式,請創建它的可重用實例,而不是調用靜態方法。 此外,如果您多次使用它,請考慮使用Compiled
選項。 它會跑得更快; 然而,代價是初始化時間更長。
var regex = new Regex(@"(?<=\[').*?(?='])", RegexOptions.Compiled);
while (loop_condition) {
List<string> TheListOfStrings = regex.Matches(input)
.Cast<Match>()
.Select(m => m.Value)
.ToList();
...
}
這可能滿足您的需求: (?<=\\[")[^"]+(?="\\])|(?<=\\[')[^']+(?='\\])
對於a['bc']d['ef']gh']
這將返回bc
和ef
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.