首页 > 解决方案 > 从字符串中间查找特定文本和对应的电子邮件 ID,并将其存储到数据表或 C# 中的列表中

问题描述

我有一个字符串如下

string error_message= "{\"2705\":\"Error importing username: 3167763, primary email: pkumar194@google.com, error: User already exists but Email does not match: pkumar194@googlee.com vs pkumar193@google.co.in\",\"10001\":\"Error importing username: 3195330, primary email: alejandra.mejia@google.com, error: User already exists but Email does not match: alejandra.mejia@google.com vs alejandra.mejia@googlee.com\"}";

从上面的字符串中,我需要找到重复的文本“导入用户名时出错:”并将其旁边的用户名值与文本“主电子邮件:”后的相应电子邮件 ID 一起存储在数据表中,预期输出如下

数据表中的预期结果如下

username    primary email
3167763     pkumar194@google.com
3195330     alejandra.mejia@google.com

下面是我拥有的代码示例,我可以在其中获取列表中的所有用户名

List<int> list = Regex.Matches(error_message, @"(?<=Error importing username: )\d+")
    .Cast<Match>()
    .Select(match => int.Parse(match.Value))
    .ToList();

标签: c#asp.netstringsplit

解决方案


您可以使用 2 个捕获组,而不是使用单个后视。

\bError importing username: (\d+), primary email: ([^\s@]+@[^\s@,]+)

正则表达式演示| C# 演示

例如

string pattern = @"\bError importing username: (\d+), primary email: ([^\s@]+@[^\s@,]+)";
string input = @"string error_message= ""{\""2705\"":\""Error importing username: 3167763, primary email: pkumar194@google.com, error: User already exists but Email does not match: pkumar194@googlee.com vs pkumar193@google.co.in\"",\""10001\"":\""Error importing username: 3195330, primary email: alejandra.mejia@google.com, error: User already exists but Email does not match: alejandra.mejia@google.com vs alejandra.mejia@googlee.com\""}"";";

var collection = Regex.Matches(input, pattern)
.Cast<Match>()
.Select(match => 
new {username = int.Parse(match.Groups[1].Value), primary_email = match.Groups[2].Value}
);

foreach (var item in collection) {
    Console.WriteLine("username: {0}, primary email: {1}", 
    item.username, 
    item.primary_email
    );
}

输出

username: 3167763, primary email: pkumar194@google.com
username: 3195330, primary email: alejandra.mejia@google.com

推荐阅读