使用RegEx大写[变量]

本文关键字:变量 大写 RegEx 使用 | 更新日期: 2023-09-27 18:06:16

我有一个c#字符串扩展,需要采取一个字符串,并将所有的[变量]替换为[变量],但我不知道从哪里开始。

Source: Hi [name] how are you [other]?
Result: Hi [NAME] how are you [OTHER]?

这是我的样板文件:

    public static string VariablesToUpperCase(this string input)
    {
        string pattern = @"'['w+']";
        string replacement = "??????";
        Regex rgx = new Regex(pattern);
        return rgx.Replace(input, replacement);
    }

使用RegEx大写[变量]

尝试如下:

 public static string VariablesToUpperCase(this string input)
    {
        string pattern = @"'['w+']";
        Regex rgx = new Regex(pattern);
        return rgx.Replace(input, (m) => { return m.ToString().ToUpper(); });
    }

我对你的图案做了改动。您需要转义括号,否则您只是匹配单个单词字符或加号的字符类。

要大写,我们使用正则表达式。替换接受MatchEvaluator参数的重载。每次匹配都会调用它,并将其替换为返回值。

另一个解决方案:

    public static string VariablesToUpperCase(this string input)
    {
        return Regex.Replace(input, @"'['w+']", delegate (Match match)
        {
            string v = match.ToString();
            return v.ToUpper();
        });
    }