简体   繁体   English

正则表达式或Linq捕获c#中的键和值对

[英]Regex or Linq to capture the key and value pair in c#

I have a string like below 我有一个像下面的字符串

Loop="start:yes " while=" end" do=" yes " Loop =“start:yes”而=“end”do =“yes”

expected string 期望的字符串
Loop="start:yes" while="end" do="Yes" Loop =“start:yes”而=“end”do =“Yes”

I tried to capture the key and value pair(ex. Loop="start:yes ") and remove the white space in each pair and then concatenate whole string as expected string above 我试图捕获键和值对(例如Loop =“start:yes”)并删除每对中的空格,然后将整个字符串连接为上面的预期字符串

        //string rx = "([\\w+\\s]*\\=?[\\s]*\\\"[\\w+\\s]*\\\")";

        string rx = ".+?\\=?[\\s]*\\\".+?\\\"";

        Console.WriteLine(rx);
        Match m = Regex.Match(tempString, rx, RegexOptions.IgnoreCase);

        if (m.Success)
        {

            Console.WriteLine(m.Groups[1].Value);    
            Console.WriteLine(m.Groups[2].Value);   
            Console.WriteLine(m.Groups[3].Value);   
            Console.WriteLine(m.Groups[4].Value);

        }

Tried above code but am unable to capture any pair in the string 尝试上面的代码,但无法捕获字符串中的任何对

You can pass a callback method to the Regex.Replace , and inside that method, populate an object of Dictionary<string, string> . 您可以将回调方法传递给Regex.Replace ,并在该方法中填充Dictionary<string, string>的对象。

You can use the following regex to grab the keys and values: 您可以使用以下正则表达式来获取键和值:

(?<key>\w+)="\s*(?<val>.*?)\s*"

The regex matches: 正则表达式匹配:

  • (?<key>\\w+) - matches and stores in a capture group names key 1 or more alphanumeric symbols or underscore (?<key>\\w+) - 匹配并存储在捕获组中的名称 1个或多个字母数字符号或下划线
  • =" - a literal =" =" - 文字="
  • \\s* - 0 or more whitespace \\s* - 0个或更多的空格
  • (?<val>.*?) - matches and captures into group names val any number of any characters but a newline as few as possible before the closest... (?<val>.*?) - 匹配并捕获组名称val任意数量的任何字符,但在最接近之前尽可能少的换行符...
  • \\s*" - 0 or more whitespace symbols followed by a " . \\s*" - 0或更多的空白符号后跟一个"

Here is the C# demo: 这是C#演示:

private Dictionary<string, string> dct = new Dictionary<string, string>();
private string callbck(Match m)
{
    dct.Add(m.Groups["key"].Value, m.Groups["val"].Value);
    return string.Format("{0}=\"{1}\"", m.Groups["key"].Value, m.Groups["val"].Value);
}

And this is the main code: 这是主要代码:

var s = "Loop=\"start:yes \" while=\" end\" do=\" yes \"";
var res = Regex.Replace(s, @"(?<key>\w+)=""\s*(?<val>.*?)\s*""",  callbck);

Result: Loop="start:yes" while="end" do="yes" , 结果: Loop="start:yes" while="end" do="yes"

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM