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

标签 c# regex

我可以在格式为 {key-value}Some text{/key} 的文本区域内有 0 个或多个子字符串,

例如这是我的{link-123}测试{/link}文本区域

我想遍历匹配此模式的任何项目,根据键和值执行和操作,然后用新字符串替换此子字符串(由基于键的操作检索的 anchor 链接) .

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

最佳答案

如果这些标签没有嵌套,那么你只需要遍历文件一次;如果可以嵌套,则需要对每一层嵌套进行一次迭代。

此答案假定大括号仅作为标记定界符出现(而​​不是,例如,在注释内部):

result = Regex.Replace(subject, 
    @"\{                # opening brace
    (?<key>\w+)         # Match the key (alnum), capture into the group 'key'
    -                   # dash
    (?<value>\w+)       # Match the value (alnum), capture it as above
    \}                  # closing brace
    (?<content>         # Match and capture into the group 'content':
     (?:                # Match...
      (?!\{/?\k<key>)   # (unless there's an opening or closing tag
      .                 # of the same name right here) any character
     )*                 # any number of times
    )                   # End of capturing group
    \{/\k<key>\}        # Match the closing tag.", 
    new MatchEvaluator(ComputeReplacement), RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);

public String ComputeReplacement(Match m) {
    // You can vary the replacement text for each match on-the-fly
    // m.Groups["key"].Value will contain the key
    // m.Groups["value"].Value will contain the value of the match
    // m.Groups["value"].Value will contain the content between the tags
    return ""; // change this to return the string you generated here
}

关于c# - 如何匹配正则表达式模式并从中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14736697/

相关文章:

c# - void 类型方法表达式主体成员允许非 void 类型的表达式*如果有其他方法*

c# - C#中的多线程压缩

c# - Windows XP 嵌入式版本出现 System.IO.IOException 的原因是什么?

c# - 为什么数据库会超时?

c# - 将主体添加到应该被覆盖的虚拟方法

javascript - 正则表达式接受至少一个字母数字字符和一个特殊字符

javascript - 正则表达式匹配空格但转义空格

javascript - 正则表达式将所有内容转换为小写,URL 除外

c++ - 我应该如何提取此 url 获取字符串

替换字符串中的第 n 个数字