我需要验证文件的文本是否包含以下格式的文本:
#0
DIRECTION: FORWARD
SPEED: 10
TIME: 10
OR
#1
DIRECTION: REVERSE
SPEED: 10
ROTATIONS: 10
这将重复多个步骤。
#
必须后跟一个数字,DIRECTION
必须后跟FORWARD
或REVERSE
,SPEED
后面必须跟一个数字和最后一行将是TIME
或ROTATIONS
后跟一个数字。
我想在开始读取值之前验证文件是否包含此格式的文本,而不是一些奇怪的值。
我可以使用某种外卡吗?我已经开始关注正则表达式,但我之前没有使用它。
我想做的是做一些比较,其中数字是通配符,这样我知道这些行是否包含基本格式:
if(fileLines[0].Matches("#%")) // Where % would be the wildcard?
if(fileLines[1].Matches("DIRECTION:%")) // Does something like this exist?
答案 0 :(得分:1)
这种模式似乎有效
string[] lines =
{
"#0",
"DIRECTION: FORWARD",
"SPEED: 10",
"TIME: 10"
};
// meaning At start of line there is a # followed by digits till the end of line
if(checkLine(@"^#\d+$", lines[0]) == false)
Console.WriteLine("False on line 1");
else
Console.WriteLine("True on line 1");
// meaning At start of line there is the word DIRECTION: followed by space and the words REVERSE or FORWARD
if(checkLine(@"^DIRECTION: (REVERSE|FORWARD)", lines[1]) == false)
Console.WriteLine("False on line 2");
else
Console.WriteLine("True on line 2");
// meaning At start of line there is the word SPEED: followed by a space and digits till the end of the line
if(checkLine(@"^SPEED: \d+$", lines[2]) == false)
Console.WriteLine("False on line 3");
else
Console.WriteLine("True on line 3");
// meaning At start of line there are the words TIME or ROTATIONS followed by colon, space and digits till the end of the line
if(checkLine(@"^(TIME|ROTATIONS): \d+$", lines[3]) == false)
Console.WriteLine("False on line 4");
else
Console.WriteLine("True on line 4");
}
// Define other methods and classes here
private bool checkLine(string regExp, string line)
{
Regex r = new Regex(regExp);
return r.IsMatch(line);
}
答案 1 :(得分:0)
如果您已将文件中的所有行都读为通用列表。
List<string> fileLines = new List<string>();
fileLines.Add("#0");
fileLines.Add("DIRECTION: FORWARD");
fileLines.Add("SPEED: 10");
fileLines.Add("TIME: 10");
fileLines.Add("#1");
fileLines.Add("DIRECTION: REVERSE");
fileLines.Add("SPEED: 10");
fileLines.Add("ROTATIONS: 10");
使用此功能验证文件是否有效
信用:史蒂夫正在实施正则表达式
public bool CheckConsistancy(List<string> fileLines)
{
bool status = false;
if (fileLines != null && fileLines.Count > 0)
{
if(fileLines.Count % 4 == 0)
{
List<List<string>> fileLineGroups = fileLines.Select((x, i) => new { Index = i, Value = x }).GroupBy(x => x.Index / 4).Select(x => x.Select(v => v.Value).ToList()).ToList();
foreach (List<string> fileLineGroup in fileLineGroups)
{
if (checkLine(@"^#\d", fileLineGroup[0]))
{
if (checkLine(@"^DIRECTION: (REVERSE|FORWARD)", fileLineGroup[1]))
{
if (checkLine(@"^SPEED: \d", fileLineGroup[2]))
{
if (checkLine(@"^(TIME|ROTATIONS): \d", fileLineGroup[3]))
{
status = true;
}
else
{
status = false;
break;
}
}
else
{
status = false;
break;
}
}
else
{
status = false;
break;
}
}
else
{
status = false;
break;
}
}
}
else
{
status = false;
}
}
return status;
}
private bool checkLine(string regExp, string line)
{
Regex r = new Regex(regExp);
return r.IsMatch(line);
}
调用该函数以检查一致性
bool status = CheckConsistancy(fileLines);