[英]Split string into tokens using 2 or more spaces
我有一個試圖解析的文本文件。 截至目前,我正在使用String.Split方法來對字符串進行標記化。
這是一些示例文本:
GP71011N Sign 1.00 each 4298.96000 4298.96
H50 ENGINE* Sign 1.00 each 9027.65000 9027.65
JR70883* Sign 1.00 each 10674.24300 10674.24
KE31453 Sign 1.00 each 1000.00000 1000.00
MK51645 Sign 6.00 each 13718.06000 82308.36
MK51649 Sign 1.00 each 14331.08000 14331.08
MK51722 Sign 4.00 each 13186.00000 52744.00
ML51651 Sign 5.00 each 15988.00000 79940.00
現在,我正在逐行讀取文件,並用一個空格刪除所有多余的空格,然后我用一個空格標記該字符串,但是現在我正在查看它……將無法工作。
這是我當前的代碼:
string output = "";
string currentPCat = "";
string currentAccount = "";
bool IsValidLine = false;
var lineNo = 1;
while ((line = file.ReadLine()) != null)
{
if(lineNo <= 36)
{
lineNo++;
}
else
{
line = Regex.Replace(line, @"\s+", " ");
var tokens = line.Split(' ');
if (tokens.Count() >= 4 && tokens.Contains("PCAT:"))
{
currentPCat = tokens[1];
currentAccount = tokens[2];
IsValidLine = true;
}
else if (tokens.Count() == 7)
{
if (IsValidLine)
{
output = output + currentPCat + "," + currentAccount + "," + tokens[1] + "," + tokens[2] + "," + tokens[3] + "," + tokens[4] + "," + tokens[5] + "," + tokens[6] + "\r\n";
}
}
else
{
IsValidLine = false;
}
lineNo++;
}
}
我真正需要更改的部分是令牌生成器,因此這部分是:
line = Regex.Replace(line, @"\s+", " ");
var tokens = line.Split(' ');
我想我需要刪除第一行,並且我希望標記被2個或更多空格標記。 我怎樣才能做到這一點?
當然-使用String.Split
的重載,該重載采用字符串定界符而不是char定界符:
var tokens = line.Split(new string[] {" "},StringSplitOptions.RemoveEmptyEntries);
.Select(s => s.Trim())
.ToArray();
如果段之間存在奇數個空格,則必須使用Trim()
刪除前導/后綴空格。
代替使用String.Split
使用Regex.Split
並為參數提供"\\s{2,}"
。
string[] tokens = Regex.Split(line, @"\s{2,}");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.