C# 捕获多行文本
我有一个txt文件,每个新闻都以C# 捕获多行文本,c#,regex,wpf,C#,Regex,Wpf,我有一个txt文件,每个新闻都以 * This is new title * this is the body thid is the body .... * This is another title * 用户通过双击从列表框中选择所需的标题。我希望我的程序再次检查该文件,并选择所选新闻的两个标题正文之间的文本 这是我当前的函数,但它所做的唯一一件事是将标题从列表框添加到文本框中,新的正文应该在其中 谢谢你的帮助 private void listBox_MouseDoubleClick(
* This is new title *
this is the body
thid is the body
....
* This is another title *
用户通过双击从列表框中选择所需的标题。我希望我的程序再次检查该文件,并选择所选新闻的两个标题正文之间的文本
这是我当前的函数,但它所做的唯一一件事是将标题从列表框添加到文本框中,新的正文应该在其中
谢谢你的帮助
private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
string text = listBox.SelectedItem.ToString();
List<string> myList = new List<string>();
string tempLineValue;
string txtFile = path.Text; //path is TextBox with file path
Regex regex = new Regex(@text + "(.*)", RegexOptions.Singleline);
using (StreamReader inputReader = new StreamReader(txtFile))
{
while (null != (tempLineValue = inputReader.ReadLine()))
{
if (regex.Match(tempLineValue).Success)
{
myList.Add((regex.Match(tempLineValue)).Value);
}
}
}
for (int i = 0; i < myList.Count; i++)
{
textBox.Text = myList.ElementAt(i);
}
}
试试这个:
private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
string text = listBox.SelectedItem.ToString();
string tempLineValue;
string txtFile = path.Text; //path is TextBox with file path
string title = null;
using (StreamReader inputReader = new StreamReader(txtFile))
{
while (null != (tempLineValue = inputReader.ReadLine()))
{
if (tempLineValue.StartsWith("*"))
title = tempLineValue.Substring(2, tempLineValue.Length - 4).Trim();
else if (text == title)
textBox.Text += tempLineValue + Environment.NewLine;
}
}
}
如果text listBox.SelectedItem变量的值为,则它应该可以工作。例如,这是没有*的新标题。您希望根据文件标题获取新闻正文。逐行读取文件是不可能的。你必须读完整的文件。之后,您可以尝试使用正则表达式搜索并获取新闻正文。我写了一篇文章,根据标题搜索你的新闻正文。我还测试了C,它对我有效。您可以尝试下面的代码 代码: 输出:
可能的重复项总是可以找到与您想要的标题相等的行,因为您确切地知道它应该是什么,并添加以下所有行,直到到达另一个标题行,然后停止。@EdPlunkett Singleline没有解决此问题。这个问题可能在正则表达式中吗?@HC1122没有解决这个问题。你能描述它做了什么吗?什么都不匹配吗?它是否匹配从所选标题到文件结尾的所有内容?它完全做了其他的事情吗?在我看来,你可以通过:1使用ReadToEnd方法读取整个文件来更快、更容易地完成它。2使用字符串。在结果上拆分“*”,这将生成一个字符串数组,您在位置i中有一个标题,在i+1中,您的内容3将您的数组转换为具有2个属性title和content的对象列表,并将此列表设置为ListBox上的items参数,displayMember设置为title。4在列表框中的selectedItemChanged事件上,只需设置textBox.text=selectedItem.content当我双击所选行时似乎什么都没有发生,也应该使用正则表达式,而不是子字符串。调试代码以找出原因。或提供您的问题的完整可复制样本:
string text = " This is new title ";
string txtFile = @"D:\New Text Document.txt"; //path is TextBox with file path
Regex regex = new Regex(@"\*" + text + @"\*(\t|\n|\r|\s)+(.*)(\t|\n|\r|\s)+(.*)(\t|\n|\r)+\*", RegexOptions.Multiline);
using (StreamReader inputReader = new StreamReader(txtFile))
{
string txt = inputReader.ReadToEnd();
Match match = regex.Match(txt);
richTextBox1.Text = match.Value.Replace("*" + text + "*", "").Replace("*", "");
}