[英]How can i parse specific string from text file reading all lines?
In each line i want to parse the string after the tag 在每一行中,我想解析标记后的字符串
<li>602 — <a href="/w/index.php?title=Text602&action=edit&redlink=1" class="new" title="Text602 (page does not exist)">Text602</a> document</li> <li>ABW — <a href="/wiki/AbiWord" title="AbiWord">AbiWord</a> Document</li>
I want to parse the 602 from the first line and the ABW from the second line. 我想从第一行解析602,从第二行解析ABW。 What i tried to do is: 我试图做的是:
private void ParseFilesTypes() { string[] lines = File.ReadAllLines(@"E:\\New folder (44)\\New Text Document.txt"); foreach (string str in lines) { int r = str.IndexOf("<li>"); if (r >= 0) { int i = str.IndexOf(" -", r + 1); if (i >= 0) { int c = str.IndexOf(" -", i + 1); if (c >= 0) { i++; MessageBox.Show(str.Substring(i, c - i)); } } } } }
But c is all the time -1 但是c一直都是-1
I think it is a case when regex would be useful (unless there will be no li
attributes): 我认为正则表达式会很有用(除非没有li
属性):
var regex = new Regex("^<li>(.+) —");
foreach (string str in lines)
{
var m = regex.Match(str);
if (m.Success)
MessageBox.Show(m.Groups[1].Value);
}
Actually, your problem is that you're reading the file with the incorrect encoding . 实际上,您的问题是您正在使用错误的编码读取文件。 You have a special character in your file —
and not -
. 你在你的文件中的特殊字符—
不-
So you need to correct this character in your code and read the file in the correct encoding. 因此,您需要在代码中更正此字符,并以正确的编码读取文件。 If you debug your string read with wrong encoding, you'll see a black diamond instead of —
. 如果您以错误的编码方式调试读取的字符串,则会看到黑色菱形而不是—
。
Also, you need to remove the space before —
or replace i + 1
with i
; 另外,您需要先删除空格—
或将i + 1
替换为i
;
private static void ParseFilesTypes()
{
string sampleFilePath = @"log.txt";
string[] lines = File.ReadAllLines(@"log.txt", Encoding.GetEncoding("windows-1252"));
foreach (string str in lines)
{
int r = str.IndexOf("<li>");
if (r >= 0)
{
int i = str.IndexOf(" —", r + 1);
if (i >= 0)
{
int c = str.IndexOf(" —", i);
if (c >= 0)
{
i++;
int startIndex = r + "<li>".Length;
int length = i - startIndex - 1;
string result = str.Substring(r + "<li>".Length, length);
MessageBox.Show(result);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.