开发者

C# Find if a word is in a document

I am looking for a way to check if the "foo" word is present in a text file using C#.

I may use a regular expression but I'm not sure that i开发者_JAVA百科s going to work if the word is splitted in two lines. I got the same issue with a streamreader that enumerates over the lines.

Any comments ?


What's wrong with a simple search?

If the file is not large, and memory is not a problem, simply read the entire file into a string (ReadToEnd() method), and use string Contains()


Here ya go. So we look at the string as we read the file and we keep track of the first word last word combo and check to see if matches your pattern.

string pattern = "foo";
string input = null;
string lastword = string.Empty;
string firstword = string.Empty;
bool result = false;

FileStream FS = new FileStream("File name and path", FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader SR = new StreamReader(FS);

while ((input = SR.ReadLine()) != null) 
{
    firstword = input.Substring(0, input.IndexOf(" "));
    if(lastword.Trim() != string.Empty) { firstword = lastword.Trim() + firstword.Trim(); } 

    Regex RegPattern = new Regex(pattern);
    Match Match1 = RegPattern.Match(input);
    string value1 = Match1.ToString(); 

    if (pattern.Trim() == firstword.Trim() || value1 != string.Empty) { result = true;  }

    lastword = input.Trim().Substring(input.Trim().LastIndexOf(" "));
}


Here is a quick quick example using LINQ

    static void Main(string[] args)
    {
        { //LINQ version
            bool hasFoo = "file.txt".AsLines()
                                    .Any(l => l.Contains("foo"));
        }
        { // No LINQ or Extension Methods needed
            bool hasFoo = false;
            foreach (var line in Tools.AsLines("file.txt"))
                if (line.Contains("foo"))
                {
                    hasFoo = true;
                    break;
                }
        }
    }
}
public static class Tools
{
    public static IEnumerable<string> AsLines(this string filename)
    {
        using (var reader = new StreamReader(filename))
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                while (line.EndsWith("-") && !reader.EndOfStream)
                    line = line.Substring(0, line.Length - 1)
                                + reader.ReadLine();
                yield return line;
            }
    }
}


What about if the line contains football? Or fool? If you are going to go down the regular expression route you need to look for word boundaries.

Regex r = new Regex("\bfoo\b");

Also ensure you are taking into consideration case insensitivity if you need to.


You don't need regular expressions in a case this simple. Simply loop over the lines and check if it contains foo.

using (StreamReader sr = File.Open("filename", FileMode.Open, FileAccess.Read))
{
    string line = null;
    while (!sr.EndOfStream) {
        line = sr.ReadLine();
        if (line.Contains("foo"))
        {
            // foo was found in the file
        }
    }
}


You could construct a regex which allows for newlines to be placed between every character.

private static bool IsSubstring(string input, string substring)
{
    string[] letters = new string[substring.Length];
    for (int i = 0; i < substring.Length; i += 1)
    {
        letters[i] = substring[i].ToString();
    }
    string regex = @"\b" + string.Join(@"(\r?\n?)", letters) + @"\b";
    return Regex.IsMatch(input, regex, RegexOptions.ExplicitCapture);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜