Ebikeneser
Ebikeneser

Reputation: 2364

Regular expression to find specific words in a text file in C#?

I have written a console app that reads in a text file full of data.

I had to extract any telephone numbers from it and put them into a results file.

I used several RegEx's to do this to cover several different formats of telephone numbers i.e. UK, US, international etc.

Here is an example of one I used -

string sPattern = "^\\d{3}-\\d{3}-\\d{4}$";

This would look for telephone numbers in the following format - 123-456-7890

My question being, I now want to write a RegEx that looks for key words as apposed to numbers.

E.g. If I read in a data file I would want it to find key words 'White' and 'Car'.

And then put them into the results file.

Is there a method of doing this?

Upvotes: 0

Views: 12512

Answers (3)

Chris McAtackney
Chris McAtackney

Reputation: 5232

Just use the word, delimited by word boundaries;

string sPattern = @"\bKeyword\b";

http://www.regular-expressions.info/wordboundaries.html

Upvotes: 2

Antoine
Antoine

Reputation: 5245

Try Regex.Matches():

string pattern = "car";
Regex rx = new Regex(pattern, RegexOptions.None);
MatchCollection mc = rx.Matches(inputText);

foreach (Match m in mc)
{
    Console.WriteLine(m.Value);
}

Upvotes: 1

Jean-Louis Mbaka
Jean-Louis Mbaka

Reputation: 1612

The method you're looking for is:

System.Text.RegularExpressions.Regex.IsMatch(string input. string pattern)

This medhod indicates if the regular expression finds a match in the input string. It returns true if there is a match, false otherwise.

http://msdn.microsoft.com/en-us/library/ms228595%28v=VS.100%29.aspx first example has what you need.

Upvotes: 1

Related Questions