我有一个名称为balamurugan,chendurpandian,......
的文本文件
如果我在文本框中给出ba
....
如果我点击提交按钮意味着我必须在文本文件中搜索值ba
并显示为pattern matched
....
我已经使用
阅读了文本文件 string FilePath = txtBoxInput.Text;
并使用
将其显示在文本框中 textBoxContents.Text = File.ReadAllText(FilePath);
但我不知道如何使用c#搜索文本文件中的单词,任何人都可以提出建议???
答案 0 :(得分:2)
您可以简单地使用:
textBoxContents.Text.Contains(keyword)
如果您的文字包含您选择的关键字,则会返回true
。
答案 1 :(得分:2)
取决于您需要的模式匹配类型 - 您可以使用简单的String.Contains
方法,也可以尝试使用正则表达式,这样您可以更好地控制搜索方式,并在同时。这里有几个链接可以帮助您快速开始使用正则表达式:
http://www.codeproject.com/KB/dotnet/regextutorial.aspx http://www.developer.com/open/article.php/3330231/Regular-Expressions-Primer.htm
答案 2 :(得分:2)
首先,您应该拆分输入字符串,之后您可以对每个值执行包含:
// On file read:
String[] values = File.ReadAllText(FilePath);
// On search:
List<String> results = new List<String>();
for(int i = 0; i < values.Length; i++) {
if(values[i].Contains(search)) results.Add(values[i]);
}
或者,如果您只想在字符串的开头或结尾搜索,可以分别使用StartsWith或EndsWith:
// Only match beginnging
values[i].StartsWith(search);
// Only match end
values[i].EndsWith(search);