从文件中提取文本 C#
Extract a text from a file c#
我收到一个 .mail 文件,其中包含:
`
FromFild=xxx@gmail.com
ToFild=yyy@gmai.com
SubjectFild=Test
Message=
<b><font size="3" color="blue">testing</font> </b>
<table>
<tr>
<th>Question</th>
<th>Answer</th>
<th>Correct?</th>
</tr>
<tr>
<td>What is the capital of Burundi?</td>
<td>Bujumburra</td>
<td>Yes</td>
</tr>
<tr>
<td>What is the capital of France?</td>
<td>F</td>
<td>Erm... sort of</td>
</tr>
</table>
Message=END
#at least one empty line needed at the end!
`
我只需要提取和保存 Message= 和 Message=END 之间的文本。
我尝试使用 split('=').Last/First()。 Not good.I 不能使用 Substring,因为它只接受 int ofIndex。我是菜鸟,我想不出解决方案。可以给个提示吗?
我假设文本文件或您正在寻找的消息中没有我可以依赖的固定行数。
string prefix = "Message=";
string postfix = "Message=END";
var text = File.ReadAllText("a.txt");
var messageStart = text.IndexOf(prefix) + prefix.Length;
var messageStop = text.IndexOf(postfix);
var result = text.Substring(messageStart, messageStop - messageStart);
您可以使用这个正则表达式:
/Message=(?<messagebody>(.*))Message=END/s
然后是获取消息的代码:
string fileContent; //The content of your .mail file
MatchCollection match = Regex.Matches(fileContent, "/Message=(?<messagebody>(.*))Message=END/s");
string message = match[0].Groups["messagebody"].Value;
我收到一个 .mail 文件,其中包含:
`
FromFild=xxx@gmail.com
ToFild=yyy@gmai.com
SubjectFild=Test
Message=
<b><font size="3" color="blue">testing</font> </b>
<table>
<tr>
<th>Question</th>
<th>Answer</th>
<th>Correct?</th>
</tr>
<tr>
<td>What is the capital of Burundi?</td>
<td>Bujumburra</td>
<td>Yes</td>
</tr>
<tr>
<td>What is the capital of France?</td>
<td>F</td>
<td>Erm... sort of</td>
</tr>
</table>
Message=END
#at least one empty line needed at the end!
`
我只需要提取和保存 Message= 和 Message=END 之间的文本。 我尝试使用 split('=').Last/First()。 Not good.I 不能使用 Substring,因为它只接受 int ofIndex。我是菜鸟,我想不出解决方案。可以给个提示吗?
我假设文本文件或您正在寻找的消息中没有我可以依赖的固定行数。
string prefix = "Message=";
string postfix = "Message=END";
var text = File.ReadAllText("a.txt");
var messageStart = text.IndexOf(prefix) + prefix.Length;
var messageStop = text.IndexOf(postfix);
var result = text.Substring(messageStart, messageStop - messageStart);
您可以使用这个正则表达式:
/Message=(?<messagebody>(.*))Message=END/s
然后是获取消息的代码:
string fileContent; //The content of your .mail file
MatchCollection match = Regex.Matches(fileContent, "/Message=(?<messagebody>(.*))Message=END/s");
string message = match[0].Groups["messagebody"].Value;