我想按逗号分隔这样的字符串:
field1:"value1", field2:"value2", field3:"value3,value4"
将其转换为一个
string[]
数组,看起来像:0 field1:"value1"
1 field2:"value2"
2 field3:"value3,value4"
我正在尝试使用Regex.Split
来做到这一点,但似乎无法弄清楚正则表达式。
使用Matches
比Split
更容易实现这个,例如:
string[] asYouWanted = Regex.Matches(input, @"[A-Za-z0-9]+:"".*?""")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
虽然如果你的值(或字段)包含转义引号(或类似的麻烦字符),那么最好使用适当的CSV解析器。
如果您的值中确实有转义引号,则我认为以下正则表达式将起作用 - 进行测试:
@"field3:""value3\\"",value4""", @"[A-Za-z0-9]+:"".*?(?<=(?<!\\)(\\\\)*)"""
(?<=(?<!\\)(\\\\)*)
是为了确保它停止匹配的"
之前只有偶数个斜杠,因为奇数个斜杠意味着它被转义。未经测试,但应该没问题:
string[] parts = string.Split(new string[] { ",\"" }, StringSplitOptions.None);
如果需要,记得在末尾添加“反斜杠”。
string[] arr = str.Split(new string[] {"\","}}, StringSplitOptions.None).Select(str => str + "\"").ToArray();
按照webnoob所提到的方法,使用\,
进行分割,然后在选择时加上尾随的"
,最后转换为数组。
stringsplitoptions
参数。你的第二条评论是什么意思? - LukeHennerley试一下这个
// (\w.+?):"(\w.+?)"
//
// Match the regular expression below and capture its match into backreference number 1 «(\w.+?)»
// Match a single character that is a “word character” (letters, digits, and underscores) «\w»
// Match any single character that is not a line break character «.+?»
// Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Match the characters “:"” literally «:"»
// Match the regular expression below and capture its match into backreference number 2 «(\w.+?)»
// Match a single character that is a “word character” (letters, digits, and underscores) «\w»
// Match any single character that is not a line break character «.+?»
// Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Match the character “"” literally «"»
try {
Regex regObj = new Regex(@"(\w.+?):""(\w.+?)""");
Match matchResults = regObj.Match(sourceString);
string[] arr = new string[match.Captures.Count];
int i = 0;
while (matchResults.Success) {
arr[i] = matchResults.Value;
matchResults = matchResults.NextMatch();
i++;
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
",
分割吗? - webnoob"
,请注意。 - LukeHennerley