【问题标题】:Regex or Linq to capture the key and value pair in c#正则表达式或 Linq 在 c# 中捕获键和值对
【发布时间】:2015-12-04 06:46:13
【问题描述】:

我有一个类似下面的字符串

Loop="start:yes" while="end" do="yes"

预期字符串
Loop="start:yes" while="end" do="Yes"

我试图捕获键和值对(例如 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);

        }

尝试了上面的代码,但无法捕获字符串中的任何对

【问题讨论】:

  • 后来发生了什么?

标签: c# regex linq


【解决方案1】:

您可以将回调方法传递给Regex.Replace,并在该方法中填充Dictionary<string, string> 的对象。

您可以使用following regex 来获取键和值:

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

正则表达式匹配:

  • (?&lt;key&gt;\w+) - 匹配并存储在捕获组名称中 1 个或多个字母数字符号或下划线
  • =" - 文字 ="
  • \s* - 0 个或多个空格
  • (?&lt;val&gt;.*?) - 匹配并捕获到组名 val 任意数量的任意字符,但在最接近之前尽可能少的换行符...
  • \s*" - 0 个或多个空格符号后跟 "

这是 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);
}

这是主要代码:

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

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

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多