我想检查特定字符串的文件内容,实际上我想检查文件是否包含' ANSWER
',以及该字符串之后到文件末尾是否有任何字符。
我怎样才能做到这一点?
ps 文件内容是动态内容,并且“ANSWER”字符串不在文件内的固定位置。
谢谢
static bool containsTextAfter(string text, string find)
{
// if you want to ignore the case, otherwise use Ordinal or CurrentCulture
int index = text.IndexOf(find, StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
int startPosition = index + find.Length;
if (text.Length > startPosition)
return true;
}
return false;
}
以这种方式使用它:
bool containsTextAfterAnswer = containsTextAfter(File.ReadAllText("path"), "ANSWER");
一种方法是将整个文件加载到内存中并进行搜索:
string s = File.ReadAllText(filename);
int pos = s.IndexOf("ANSWER");
if (pos >= 0)
{
// we know that the text "ANSWER" is in the file.
if (pos + "ANSWER".Length < s.Length)
{
// we know that there is text after "ANSWER"
}
}
else
{
// the text "ANSWER" doesn't exist in the file.
}
或者,您可以使用正则表达式:
Match m = Regex.Match(s, "ANSWER(.*)");
if (m.Success)
{
// the text "ANSWER" exists in the file
if (m.Groups.Count > 1 && !string.IsNullOrEmpty(m.Groups[1].Value))
{
// there is text after "ANSWER"
}
}
else
{
// the text "ANSWER" does not appear in the file
}
在正则表达式的情况下,“ANSWER”的位置将是 in m.Index
,而“ANSWER”之后的文本的位置将是 in m.Groups[1].Index
。