how to find a string pattern and print it from my text file using C#
i have a text file with string "abcdef"
I want to search for the string "abc" in my test file ... and print the next two charac开发者_开发技巧ter for abc ..here it is "de".
how i could accomplish ? which class and function?
Try this:
string s = "abcde";
int index = s.IndexOf("abc");
if (index > -1 && index < s.Length - 4)
Console.WriteLine(s.SubString(index + 3, 2));
Update: tanascius noted a bug. I fixed it.
Read you file line by line an use something like:
string line = "";
if line.Contains("abc") {
// do
}
Or you could use regular expressions.
Match match = Regex.Match(line, "REGEXPRESSION_HERE");
In order to print all instances you can use the following code:
int index = 0;
while ( (index = s.IndexOf("abc", index)) != -1 )
{
Console.WriteLine(s.Substring(index + 3, 2));
}
This code assumes there will always be two characters after the string instance.
I think this is a more clear example:
// 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));
}
Note that this only works for the first coincidence. I dunno if you want to show all the coincidences.
精彩评论