c# - 从字符串中间查找特定文本和对应的电子邮件 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();
解决方案
您可以使用 2 个捕获组,而不是使用单个后视。
\bError importing username: (\d+), primary email: ([^\s@]+@[^\s@,]+)
例如
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
推荐阅读
- python - 根据 ID 合并 RabbitMQ 队列
- javascript - 如何使用 vue native 使用 expo-camera 拍摄照片?
- regex - Perl 正则表达式锚 $ 如何实际处理尾随换行符?
- python - 无法添加计算方法
- swiftui - 如何将核心位置重置为 ASK 以获得在 swiftUI 中请求位置的权限?
- reactjs - 赛普拉斯热重载失败
- python - 空白断言错误 - 找不到问题区域
- css - 如何缩放居中的图像以填充其父级?
- c++ - 如何查找是否找不到 websocket::stream::async_handshake() 的“目标”?
- entity-framework - EF Core - 如何定义基于两个不同名称的外部字段的一对一关系?