从字符串 c# 中获取特定单词
本文关键字:单词 获取 字符串 | 更新日期: 2023-09-27 18:30:28
我正在做一个最后一年的项目。我有一个包含一些文本的文件。我需要从这个文件中获取包含"//jj"标签的单词。例如 abc//jj、bcd//jj 等。
假设文件包含以下文本
ffafa adada//bb adad ssss//jj aad adad adadad aaada dsdsd//jj DSDSD sfsfhf//vv DFDFDF
我需要与//jj 标签相关的所有单词。这几天我被困在这里。我正在尝试的代码
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
string filename = string.Empty;
if (result == true)
{
// Open document
filename = dlg.FileName;
FileNameTextBox.Text = filename;
}
string text;
using (var streamReader = new StreamReader(filename, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
string FilteredText = string.Empty;
string pattern = @"(?<before>'w+) //jj (?<after>'w+)";
MatchCollection matches = Regex.Matches(text, pattern);
for (int i = 0; i < matches.Count; i++)
{
FilteredText="before:" + matches[i].Groups["before"].ToString();
//Console.WriteLine("after:" + matches[i].Groups["after"].ToString());
}
textbx.Text = FilteredText;
我找不到我的结果,请帮助我。
有了LINQ
,你可以用一行来做到这一点:
string[] taggedwords = input.Split(' ').Where(x => x.EndsWith(@"//jj")).ToArray();
你所有的//jj 单词都会在那里...
就我个人而言,我认为正则表达式是矫枉过正的,如果这绝对是字符串的外观。您还没有指定您绝对需要使用正则表达式,那么为什么不尝试一下呢?
// A list that will hold the words ending with '//jj'
List<string> results = new List<string>();
// The text you provided
string input = @"ffafa adada//bb adad ssss//jj aad adad adadad aaada dsdsd//jj dsdsd sfsfhf//vv dfdfdf";
// Split the string on the space character to get each word
string[] words = input.Split(' ');
// Loop through each word
foreach (string word in words)
{
// Does it end with '//jj'?
if(word.EndsWith(@"//jj"))
{
// Yes, add to the list
results.Add(word);
}
}
// Show the results
foreach(string result in results)
{
MessageBox.Show(result);
}
结果是:
ssss//jj
DSDSD//JJ
显然,这并不像正则表达式那样强大,但是您没有为我提供更多细节。
你的正则表达式中有一个额外的空间,它假设在"//jj"之前有一个空格。你想要的是:
string pattern = @"(?<before>'w+)//jj (?<after>'w+)";
此正则表达式将生成您要查找的单词:
string pattern = "(''S*)''/''/jj"
没有反斜杠转义更好一点:
('S*)'/'/jj
匹配项将包括//jj
但您可以从第一个括号组中获取单词。