我是相當新的,我無法得到這個正常工作。c#使用正則表達式來解析引號之間的字符串
我有這個字符串
[ 「字符串1」, 「字符串2」, 「STRING3」, 「串,4」, 「STRING5」, 「string6」, 「string7」, 「string8」, 「string9」 「string10」]
而且我想要得到的「
我認爲,正則表達式將是最好的做任務。
感謝您的幫助。
之間的所有值我是相當新的,我無法得到這個正常工作。c#使用正則表達式來解析引號之間的字符串
我有這個字符串
[ 「字符串1」, 「字符串2」, 「STRING3」, 「串,4」, 「STRING5」, 「string6」, 「string7」, 「string8」, 「string9」 「string10」]
而且我想要得到的「
我認爲,正則表達式將是最好的做任務。
感謝您的幫助。
之間的所有值這將引號之間捕捉:
(?<=")[\w]+(?!=")
的擴展案例:
string s = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]";
foreach (Match m in Regex.Matches(s, "(?<=\")[\\w]+(?!=\")")) {
Console.WriteLine(m.Value);
}
OP,這是比分裂版本更好的答案 – 2012-08-10 13:44:01
@RyanCopley你能解釋爲什麼你認爲它比分割字符串更好嗎?IMO使用正則表達式來簡化像這樣的字符串操作是矯枉過正的。它使用分割比使用正則表達式更有效... – James 2012-08-10 13:48:16
單個使用場景的效率是值得商榷的..但後來我們猜測:)我希望它以某種方式提供幫助無論如何:) – 2012-08-10 14:11:19
在我看來,這是爲Split
,而不僅僅是正則表達式工作:
string str = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]";
Regex rgx = new Regex("[\\[\\]\"]"); // get rid of the quotes and braces
str = rgx.Replace(str,"");
string [] split = str.Split(','); // split on commas. that's it.
foreach (string s in split)
{
Console.WriteLine(s);
}
這不需要特殊的匹配正則表達式,如果你引用的字符串變得混亂,你可能會改變它。因此,它(再次,在我看來)更加優雅。
如果你的意思是你有一個CSV字符串,例如
"\"string1\", \"string2\", \"string3\""
然後,你不需要爲微不足道,因爲這東西正則表達式,你可以使用String.Split與LINQ灑:
var values = csvString.Split(',').Select(s => s.Replace("\"", "").Trim());
因爲這看起來像JSON,請嘗試使用JavaScriptSerializer類
string myString = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]";
string[] strings = (new JavaScriptSerializer()).Deserialize<string[]>(myString);
foreach (string str in strings)
{
Console.WriteLine(str);
}
有點似乎矯枉過正。
這不是一個字符串? – Thomas 2012-08-10 13:24:47
這不是一個字符串。 – Polyfun 2012-08-10 13:24:55
那是什麼? – maddo7 2012-08-10 13:26:17