c# - 需要正则表达式逻辑来查找字符串
问题描述
我想从一个句子中找到一个特定的字符串(单词)。
给定字符串:
“在给定的健康计划中,您的计划名称:医疗和计划类型:PPO,其生效日期:2019-01-01,保险价值为 100 美元和 200 美元”。
- 如果我通过
"Plan Name:"
了,那么我的输出将是"Medical"
. - 如果我通过
"Plan Type:"
了,那么我的输出将是"PPO"
. - 如果我通过
"effective date:"
了,那么我的输出将是"2019-01-01"
. - 如果我通过
"coverage value"
了,那么在这种情况下我需要两个值。最小值"$100"
和最大值"$200"
。
同样,我需要给定句子中的电子邮件地址。在某些情况下,我只需要从给定的句子中提取日期、电子邮件或数值。在这种情况下,我没有任何先前的值可以匹配。
我需要一个涵盖所有上述要求的正则表达式逻辑。
解决方案
尝试以下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication118
{
class Program
{
static void Main(string[] args)
{
string input = "In a given health plan your Plan Name: Medical and Plan Type: PPO whose effective date: 2019-01-01 and coverage value $100 and $200";
string pattern = @"(?'key'\w+):\s+(?'value'[-\d\w]+)|(?'key'\w+)\s+(?'value'\$\d+\s+and\s+\$\d+)";
MatchCollection matches = Regex.Matches(input, pattern);
Dictionary<string, string> dict = matches.Cast<Match>()
.GroupBy(x => x.Groups["key"].Value, y => y.Groups["value"].Value)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
foreach (Match match in matches)
{
Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);
}
Console.ReadLine();
}
}
}
推荐阅读
- angular - 如何实现
在 Angular 7 中? - php - 如何在服务器端修复“当多个 mp3 文件处理为一个时,FFmpeg 命令无法工作”
- indexing - 有没有办法随时随地查看 solr 索引
- excel - A列包含divagar1,B列包含500行的siva1,我需要C列值为divagar1.siva@gmail.com
- c# - 字符串长度超过 maxJsonLength 属性
- mobile - 颤动 - 如何在颤动中保存状态选择的单选按钮列表?
- javascript - 如何在 javascript 中使用 Loop 复制 HTML 元素
- mysql - Spring Boot + JPA [Hibernate backed] + mysql = 数据截断:第 1 行的列“ATTRIBUTE_NAME”的数据太长
- amazon-web-services - 如何解决从 Amazon lex 获得的 424 (Failed Dependency) (python)?
- rpa - 通过 Automation Anywhere 访问 500 次后,SAP 运行速度变慢