开发者

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

开发者 https://www.devze.com 2023-02-26 00:37 出处:网络
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 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 f开发者_如何学Cile.

Is there a method of doing this?


Just use the word, delimited by word boundaries;

string sPattern = @"\bKeyword\b";

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


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);
}


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.

0

精彩评论

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