【发布时间】:2017-03-06 14:42:47
【问题描述】:
我有txt 文件,每个新闻都以该文件开头
* This is new title *
this is the body
thid is the body
....
* This is another title *
用户从ListBox 中选择他想要的标题(双击)。我希望我的程序再次检查文件并选择两个标题之间的文本(所选新闻的正文)。
这是我当前的功能,但它唯一要做的就是将标题从ListBox 添加到TextBox(应该是新正文的位置)。
感谢您的帮助。
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);
}
}
【问题讨论】:
-
总能找到与您想要的标题相同的行(因为您确切知道它应该是什么)并添加所有后续行直到到达另一个标题行,然后停止。
-
@EdPlunkett Singleline 没有解决问题。问题可能出在正则表达式中吗?
-
@HC1122 “没有解决问题”。你能描述它做了什么吗?它没有匹配任何东西吗?它是否匹配从所选标题到文件末尾的所有内容?它完全做了其他事情吗?
-
IMO 你可以通过以下方式更快更容易地做到这一点:1)使用“ReadToEnd”方法读取整个文件。 2)在结果上使用 string.split('*'),这将产生一个字符串数组,其中你在位置“i”有一个标题,在“i+1”你的内容 3)将你的数组转换为对象列表具有 2 个属性“title”和“content”,并将此列表设置为 ListBox 上的“items”参数,“displayMember”设置为“title”。 4)在您的 listBox 中的 selectedItemChanged 事件上,只需设置 textBox.text = selectedItem.Content