如何在文本文件的行中获取特定句子?

时间:2016-12-03 19:09:46

标签: c# string visual-studio text line

在visual C#中,我正在实现的按钮需要读取.txt文件并检查文本文件中的每一行是否以某个字符结束,如果是,则在该行上取名称并将其打印到一个消息框。到目前为止,我已设法使条件检查行的末尾是否存在指定字符,但无法获取其中的名称,因为它位于两组数字之间。该名称就在该行的第一个字符之后,就在一组数字开始之前,因为它们是用户的ID。

这是我目前在按钮内的代码:

private void button1_Click(object sender, EventArgs e)
    {
        string line, lastchar;
        // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader(@"rato.txt");
        while ((line = file.ReadLine()) != null)
        {
            lastchar= line.Substring(line.Length - 1, 1);
            if (lastchar== "2") MessageBox.Show("Prints the name of the user here");
        }
        file.Close();
    }

这是文本文件:

1Paulo111.111.111-11addaqwe2
2Rambo425.433-628-43ererssd3
1Momba111.111.111-11asdsad4432
1Mauricio111.111.111-22wwcssfd2
1Saulo111.111.111-11qwe1231231

因此按钮需要检查当前行是否以'2'结尾并在行中打印名称。例如,第一行中的名称是 Paulo ,当它以“2”结尾时,“Paulo”将打印到消息框,就像第三行和第四行一样。否则,它会跳到下一行。 然后将其打印在消息框中:“ Paulo,Momba,Mauricio。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

var names = File.ReadLines(filename)
                .Where(line => line.EndsWith("2"))
                .Select(line => Regex.Match(line, @"\p{L}+").Value)
                .ToList();

这将返回包含Paulo, Momba, Mauricio.

的列表

PS: \p{L}:任何unicode字母。

相关问题