そのような文字列をコンマで分割しようとしています:
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 で分割し"
、選択を使用して末尾にサフィックスを付けてから、配列にキャストします。
これを試して
// (\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
}