C# 如何找到字符串模式并使用C从文本文件打印它#
我有一个字符串为“abcdef”的文本文件 我想在我的测试文件中搜索字符串“abc”。。。然后打印abc的下两个字符。这里是“de” 我怎样才能做到?C# 如何找到字符串模式并使用C从文本文件打印它#,c#,.net,string,C#,.net,String,我有一个字符串为“abcdef”的文本文件 我想在我的测试文件中搜索字符串“abc”。。。然后打印abc的下两个字符。这里是“de” 我怎样才能做到? 哪个类和函数?逐行阅读您的文件,并使用类似于: string line = ""; if line.Contains("abc") { // do } 或者可以使用正则表达式 Match match = Regex.Match(line, "REGEXPRESSION_HERE"); 试试这个: string s = "abcde
哪个类和函数?逐行阅读您的文件,并使用类似于:
string line = "";
if line.Contains("abc") {
// do
}
或者可以使用正则表达式
Match match = Regex.Match(line, "REGEXPRESSION_HERE");
试试这个:
string s = "abcde";
int index = s.IndexOf("abc");
if (index > -1 && index < s.Length - 4)
Console.WriteLine(s.SubString(index + 3, 2));
string s=“abcde”;
int index=s.IndexOf(“abc”);
如果(索引>-1&&index
更新:tanascius注意到一个bug。我修复了它。为了打印所有实例,您可以使用以下代码:
int index = 0;
while ( (index = s.IndexOf("abc", index)) != -1 )
{
Console.WriteLine(s.Substring(index + 3, 2));
}
这段代码假设字符串实例后面总是有两个字符。我认为这是一个更清楚的示例:
// Find the full path of our document
System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
string path = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "MyTextFile.txt");
// Read the content of the file
string content = String.Empty;
using (StreamReader reader = new StreamReader(path))
{
content = reader.ReadToEnd();
}
// Find the pattern "abc"
int index = -1; //First char index in the file is 0
index = content.IndexOf("abc");
// Outputs the next two caracters
// [!] We need to validate if we are at the end of the text
if ((index >= 0) && (index < content.Length - 4))
{
Console.WriteLine(content.Substring(index + 3, 2));
}
//查找文档的完整路径
System.IO.FileInfo ExecutableFileInfo=new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
string path=System.IO.path.Combine(ExecutableFileInfo.DirectoryName,“MyTextFile.txt”);
//读取文件的内容
string content=string.Empty;
使用(StreamReader=新StreamReader(路径))
{
content=reader.ReadToEnd();
}
//找到“abc”模式
int指数=-1//文件中的第一个字符索引是0
索引=content.IndexOf(“abc”);
//输出下两个字符
//[!]我们需要确认我们是否在课文末尾
如果((索引>=0)和&(索引
注意这只适用于第一次巧合。我不知道你是否想展示所有的巧合。你想做
Match(内容,“abc(…))
或类似的东西后面的两个字符不能是换行符?那么您的模式abd
总是在一行内,在同一行中后跟两个字符?