[英]Regular expression to help in splitting a string
我有以下格式的字符串:
文件 = " \\r\\n 6 : size=70 : <Message body> \\r\\n 4 : size=3 : Test.txt \\r\\n 17 : size=24 : Test2.txt"
我想編寫一個正則表達式以去除所有空白,然后將字符串分成字符串數組,如下所示:
stringArray [0] = "6:size=70:<Message body>"
stringArray [1] = "4:size=3:Test.txt"
stringArray [2] = "17:size=24:Test2.txt"
我正在嘗試這樣做:
Regex pattern = new Regex(@"\s", RegexOptions.Compiled);
files = pattern.Replace(files, String.Empty);
string[] scores = files.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
但是問題在於我的正則表達式甚至剝離了“ \\ r \\ n”,因此我無法通過Environment.NewLine對其進行拆分,那么如何實現此行為?
編輯 :我忽略了一件事。 在<Message body>
或任何其他拆分字符串中分割時,我想保留空格,因此實際上我需要在最后一個冒號的第一個字符之后但在\\ r \\ n的最后一個字符之前保留空格。例如, <Message body>
或Test 3.txt
應保留空格。
編輯 :我想先使用正則表達式,然后再分割,
在常規表達式中,“ \\ s”匹配包括換行符在內的空格字符,因此為避免刪除新行,請用單個空格替換\\ s。
Regex pattern = new Regex(@" ", RegexOptions.Compiled);
這是沒有正則表達式的方法。
string x = " \r\n 6 : size=70 : <Message body> \r\n 4 : size=3 : Test.txt \r\n 17 : size=24 : Test2.txt";
string[] scores = x.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim())
.Where(p => p!=string.Empty).ToArray();
從輸入/輸出的狀態來看,我真正想要做的是在每個\\ r \\ n上分割,然后有選擇地替換空格。
如果您需要執行regex-> split,那么這是一個可行的解決方案(考慮到非常有限的輸入)。
static void Main(string[] args)
{
var s = " \r\n 6 : size=70 : <Message body> \r\n 4 : size=3 : Test.txt \r\n 17 : size=24 : Test2.txt";
var pattern = "\n.*";
var match = Regex.Match(s, pattern);
while (match.Success)
{
Console.WriteLine(match.Value.Trim().Replace(" : ", ":"));
match = match.NextMatch();
}
Console.ReadKey();
}
另外,這是一個單行解決方案,盡管不太容易理解,IMO:
static void Main(string[] args)
{
var s = " \r\n 6 : size=70 : <Message body> \r\n 4 : size=3 : Test.txt \r\n 17 : size=24 : Test2.txt";
var pattern = "\n.*";
Regex.Matches(s, pattern).Cast<Match>().Select(match => match.Value.Trim().Replace(" : ", ":")).ToList().ForEach(Console.WriteLine);
Console.ReadKey();
}
var s = " \r\n 6 : size=70 : <Message body> \r\n 4 : size=3 : Test.txt \r\n 17 : size=24 : Test 2.txt";
var split = s.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
var results = split.Select(x =>
{
var lastColonIndex = x.LastIndexOf(":");
int nonWhiteSpaceIndex = lastColonIndex + 1;
for(; nonWhiteSpaceIndex < x.Length; ++nonWhiteSpaceIndex)
{
if(!char.IsWhiteSpace(x[nonWhiteSpaceIndex]))
{
nonWhiteSpaceIndex.Dump();
break;
}
}
return (x.Substring(0, nonWhiteSpaceIndex).Replace(" ", "") + x.Substring(nonWhiteSpaceIndex)).Trim();
}).Where(x => !string.IsNullOrWhiteSpace(x)).Dump();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.