這裏是我的字符串:正則表達式打破字符串C#
1-1 This is my first string. 1-2 This is my second string. 1-3 This is my third string.
我怎樣才能打破像C#一樣;
result[0] = This is my first string.
result[1] = This is my second string.
result[2] = This is my third string.
這裏是我的字符串:正則表達式打破字符串C#
1-1 This is my first string. 1-2 This is my second string. 1-3 This is my third string.
我怎樣才能打破像C#一樣;
result[0] = This is my first string.
result[1] = This is my second string.
result[2] = This is my third string.
IEnumerable<string> lines = Regex.Split(text, "(?:^|[\r\n]+)[0-9-]+ ").Skip(1);
編輯:如果你想在數組中的結果,你可以做string[] result = lines.ToArray()
;
線將與換行,回車或兩個端,該拆分字符串與所有行結束線。
using System.Text.RegularExpressions;
...
var lines = Regex.Split(input, "[\r\n]+");
然後,你可以做你想要的每一行。
var words = Regex.Split(line[i], "\s");
行結束是不可能的,但我想從1-1,1-2和1-3分裂。 – fawad
Regex regex = new Regex("^(?:[0-9]+-[0-9]+)(.*?)$", RegexOptions.Multiline);
var str = "1-1 This is my first string.\n1-2 This is my second string.\n1-3 This is my third string.";
var matches = regex.Matches(str);
List<string> strings = matches.Cast<Match>().Select(p => p.Groups[1].Value).ToList();
foreach (var s in strings)
{
Console.WriteLine(s);
}
我們使用正則表達式多,所以^
和$
是開始和行結束。我們跳過一個或多個數字,一個-
,一個或多個數字和一個空格(?:[0-9]+-[0-9]+)
。我們懶洋洋地(*?
)採取一切(.
)否則,直到行(.*?)$
結束後,懶洋洋地使該行$
的到底是比任何字符.
然後更「重要」我們把比賽的List<string>
使用LINQ。
+1非常漂亮的使用Split + ^跳過 – xanatos
這個邏輯不起作用... – fawad
@fawad我用你的示例字符串測試過它。檢查你的代碼。 –