我有一个字符串,我想从中提取包含在两个字符串之间的字符串列表:['
和 ']
。我尝试了几个我在网上找到的正则表达式规则(特别是 this question),但问题在于正确转义字符以使正则表达式工作。
如何提取两个字符串之间的字符串列表?我想做这样的事情:
List<string> TheListOfStrings = Regex.Matches(TheText, "....");
源是一个 JavaScript block ,我想从中提取对象键:例如,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);
关于c# - 正则表达式提取两个字符串之间的字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23314575/