[英]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 ie UK, US, international etc. 我使用了几种RegEx来覆盖多种不同格式的电话号码,例如英国,美国,国际等。
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 这将查找以下格式的电话号码-123-456-7890
My question being, I now want to write a RegEx that looks for key words as apposed to numbers. 我的问题的存在,我现在想写一个正则表达式,以查找关键词作为并列为数字。
Eg If I read in a data file I would want it to find key words 'White' and 'Car'. 例如,如果我读一个数据文件,我希望它找到关键词“ White”和“ Car”。
And then put them into the results file. 然后将它们放入结果文件。
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 http://www.regular-expressions.info/wordboundaries.html
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. 如果存在匹配项,则返回
true
,否则返回false
。
http://msdn.microsoft.com/en-us/library/ms228595%28v=VS.100%29.aspx first example has what you need. http://msdn.microsoft.com/zh-cn/library/ms228595%28v=VS.100%29.aspx第一个示例具有您所需要的。
Try Regex.Matches(): 尝试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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.