读两行之间的字符串 [英] Reading a string between two lines

查看:72
本文介绍了读两行之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我在telnet控制台上获得如下输出,





----------------(第1行)

星期四88669(第2行)

---- ------------(第3行)

请输入日期(第4行)



我想看看line1和line3之间的字符串使用C#代码。



可以索引方法帮助找到第2行的字符串



我尝试过:



子串方法检查。

Hi,

I am getting an output on telnet console like below,


----------------(line1)
THURSDAY 88669(line2)
----------------(line3)
Please enter date(line4)

I want to read the string between line1 and line3 Using C# code.

can indexof method help to find the string on line 2

What I have tried:

substring method checked .

推荐答案

好吧,也许 - 但这取决于你在阅读数据时所做的事情。

如果你使用File.ReadAllLines,那么teh文件中的每一行都将在数组的一个单独元素中,所以这样可行:

Well, maybe - but it depends on what you are doing when you read the data.
If you use File.ReadAllLines, then each line from teh file will be in a separate element of the array, so this would work:
string[] lines = File.ReadAllLines(path);
if (lines.Length >= 3)
    {
    string line2 = lines[1];
    //...
    }

但是...那不会检查数据是否符合你的想法!

你可能想考虑正则表达式吗?





如果你想要一个正则表达式,那么这可能有用:

But...that doesn't check that the data is what you think it is!
You might want to consider a regex?

[edit]
If you do want a regex, then this may work:

string data = File.ReadAllText(path);
Match m = Regex.Match(data, @"(?<=-+\r\n).*?(?=\r\n-+\r\n)", RegexOptions.Multiline);
if (m.Success)
    {
    string line = m.Value;
    ...
    }





[/ edit]



[/edit]


读一行,检查它是否都是连字符。然后阅读下一行并使用String.Split将日期与日期分开。如果有更多条目,您可以通过该文件重复此操作。
Read a line, and check if it is all hyphens. Then read the next line and use String.Split to separate the day from the date. You can repeat that through the file if there are more entries.


这篇关于读两行之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆