首页 > 解决方案 > 需要正则表达式逻辑来查找字符串

问题描述

我想从一个句子中找到一个特定的字符串(单词)。

给定字符串:

“在给定的健康计划中,您的计划名称:医疗和计划类型:PPO,其生效日期:2019-01-01,保险价值为 100 美元和 200 美元”。

  1. 如果我通过"Plan Name:"了,那么我的输出将是"Medical".
  2. 如果我通过"Plan Type:"了,那么我的输出将是"PPO".
  3. 如果我通过"effective date:"了,那么我的输出将是"2019-01-01".
  4. 如果我通过"coverage value"了,那么在这种情况下我需要两个值。最小值"$100"和最大值"$200"

同样,我需要给定句子中的电子邮件地址。在某些情况下,我只需要从给定的句子中提取日期、电子邮件或数值。在这种情况下,我没有任何先前的值可以匹配。

我需要一个涵盖所有上述要求的正则表达式逻辑。

标签: c#

解决方案


尝试以下:

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();
        }
    }
}

推荐阅读