【问题标题】:How to capitalize regex numbered group如何大写正则表达式编号组
【发布时间】:2012-09-26 20:18:58
【问题描述】:

假设我有一个正则表达式模式,我想用其他东西替换该模式的匹配项。在当前模式中,有两组匹配,每组都有编号($1 和 $2):

Regex pattern = new Regex(@"\[([a-zA-Z0-9_\-]+)\^=([^\]]+)\]");
string replacement = "[starts-with(@$1,$2)]";

示例 CSS 选择器:

[id^="blah"]

预期输出:

[start-swith(@ID,"blah")] // Note ID is capitalized

这是另一个正则表达式模式:

Regex pattern = new Regex(@"\[([a-zA-Z0-9_\-]+)\*=([^\]]+)\]");
string replacement = "[contains(@$1,$2)]");

当我执行替换时,有没有办法将组 $1 中的匹配大写?

注意:我有许多模式被添加到列表中,并且它们与它们的替换字符串配对,因此我必须使解决方案适用于所有需要将某些匹配组大写的替换。

更新

我想我只是想到了一个可能的解决方案:将替换字符串转换为MatchEvaluator,并在需要时返回大写的组匹配项。我认为这可能有效:

Regex pattern = new Regex(@"\[([a-zA-Z0-9_\-]+)\^=([^\]]+)\]");
MatchEvaluator evaluator = new MatchEvaluator((Match m) =>
    {
        return string.Format("[starts-with(@{0},{1})]", m.Groups[1].Value.ToUpper(), m.Groups[2].Value);
    });

如果有人能想到更好的解决方案,请告诉我。非常感谢!

【问题讨论】:

  • 您的预期输出的一些示例将有助于阐明您的意图。
  • @tom_yes_tom 我添加了一个示例。然而,我突然意识到我可以使用 MatchEvaluator 并选择组。
  • char c += ('A' - 'a') 技巧在 c# 中有效吗?

标签: c# regex


【解决方案1】:

MatchEvaluator 很好,以为你烧了我 ;) 无论如何:

var pattern = @"([a-z]+) ([a-z]+)";
var format = "[starts-with({0}{1}]";

var input = "bla bla";
var result = ReplacePattern(input, pattern, format);

public static string ReplacePattern(string input, string pattern, string format)
{
   if (Regex.Match(input, pattern).Groups.Count != 3) return input;//or throw, or...
   return Regex.Replace(input, pattern, x =>
            string.Format(format,
                          x.Groups[1].Value.ToUpper(), 
                          x.Groups[2].Value));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多