c# - 正则表达式的问题

标签 c# regex

Date: Sun, 31 Oct 2010 21:12:24 +0600
From: [email protected]
X-Priority: 3 (Normal)
Message-ID: <[email protected]>
To: [email protected]
Subject: MySubject
MIME-Version: 1.0
Content-Type: text/plain; charset=windows-1251
Content-Transfer-Encoding: quoted-printable

Hello from Jim.

帮助获取信息。我需要在数组中包含以下内容:

Sun, 31 Oct 2010 21:12:24
[email protected]
[email protected]
MySubject
Hello from Jim

如果可以通过正则表达式实现。谢谢。

更新:不一定通过正则表达式。

最佳答案

您可以使用以下代码创建键与值的字典。它假设键是唯一的。

var lookupDictionary=
    Regex
        .Matches(src, "(.+?): (.+)", RegexOptions.Multiline)
        .Cast<Match>()
        .ToDictionary(m => m.Groups[1].Value,m => m.Groups[2].Value);

因此,要获取 To 字段,您可以:

lookupDictionary["To"]

要抓取正文,您需要一个单独的表达式:

var match=Regex.Match(src, "(?<=.*\n\n).*");
var body=match.Success ? match.Value : null;

您可能会处理 CRLF 行结尾,在这种情况下,正则表达式将是:

var match=Regex.Match(src, "(?<=.*\r\n\r\n).*");
var body=match.Success ? match.Value : null;

关于c# - 正则表达式的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4077052/

相关文章:

c# - 如何使用 OpenFileDialog 类使其默认在网络区域打开?

regex - 匹配或没有匹配项时留空

python re - 在一个大字符串中提取一个人的聊天文本

正则表达式问题 : Match sequence only n times on a random place

c# - 数据行错误,集合已修改;枚举操作可能不会执行

c# - 使用 Reflection.Emit 实现接口(interface)

c# - 将通用参数绑定(bind)到 Web API 中的自定义模型绑定(bind)器

ruby-on-rails - 带有 ruby​​ on rails 形式的正则表达式模式

javascript - 如何限制 AngularJS 中的文本字段符号?

c# - Google 数据 API 授权重定向 URI 不匹配