簡體   English   中英

從字符串c#中獲取特定單詞

[英]Get specific words from string c#

我正在做一個最后一年的項目。 我有一個包含一些文本的文件。 我需要從包含“// 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但您可以從第一個括號內的組中獲取該單詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM