如何匹配正则表达式模式并从中提取数据

时间:2013-02-06 19:00:53

标签: c# regex

我可以在{key-value}Some text{/key}

格式的文本区域中包含0个或多个子字符串

例如This is my {link-123}test{/link} text area

我想迭代匹配此模式的任何项目,基于键和值执行和操作,然后用新字符串替换此子字符串(基于键的操作检索的锚链接)

我如何在C#中实现这一目标?

2 个答案:

答案 0 :(得分:1)

这样的东西?

Regex.Replace(text,

  "[{](?<key>[^-]+)-(?<value>[^}])[}](?<content>.*?)[{][/]\k<key>[}]",
  match => {

    var key = match.Groups["key"].Value;
    var value= match.Groups["value"].Value;
    var content = match.Groups["content"].Value;

  return string.format("The content of {0}-{1} is {2}", key, value, content);
});

答案 1 :(得分:0)

使用.net正则表达式库。以下是使用Matches方法的示例:

http://www.dotnetperls.com/regex-matches

要替换文本,请考虑使用模板引擎,例如Antlr

http://www.antlr.org/wiki/display/ANTLR3/Antlr+3+CSharp+Target

以下是“匹配博客”中的示例

使用System; 使用System.Text.RegularExpressions;

class Program
{
static void Main()
{
// Input string.
const string value = @"said shed see spear spread super";

// Get a collection of matches.
MatchCollection matches = Regex.Matches(value, @"s\w+d");

// Use foreach loop.
foreach (Match match in matches)
{
    foreach (Capture capture in match.Captures)
    {
    Console.WriteLine("Index={0}, Value={1}", capture.Index, capture.Value);
    }
}
}
}

有关C#正则表达式语法的更多信息,您可以使用此备忘单:

http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

相关问题