首页 > 解决方案 > 正则表达式在句子中提取两个字符串

问题描述

我希望提取下面的两个字符串以成为 ABC-DEF 。什么是一个好的正则表达式来做到这一点?

位置之前的数据包 =“ABC” 位置之后的数据包 =“DEF”

标签: regex

解决方案


尝试以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "data-package-before-location=\"ABC\" data-package-after-location=\"DEF\"";
            string pattern = @"(?'key'[\w-]+)=""(?'value'\w+)""";

            MatchCollection matches = Regex.Matches(input, pattern);

            foreach (Match match in matches.Cast<Match>())
            {
                Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);
            }
            Console.ReadLine();
        }
    }
}

推荐阅读