繁体   English   中英

如何将字符串中的 [city] 替换为 [City]

[英]How I can replace [city] to [City] in string

我想替换[city], [cIty], [ciTY], ...[City]
我认为正则表达式是一个很好的解决方案,但我不擅长正则表达式。

试过的代码:

var text = "[City] [CIty] [ciTY] [city] [CITy]";

if (text.Contains("[city]"))
{
    //text = text.Replace("[city]", "[City]");
    text = Regex.Replace(text, @"[city]", "[City]");
    textbox.Text = text;

    textbox.SelectionStart = textbox.Text.Length;
    textbox.SelectionLength = 0;
}

除了输出

[市] [市] [市] [市] [市]

这是行不通的,因为regex语法没有完成

三点:

  1. 要匹配文本中的括号[] ,您需要在正则表达式中对它们进行转义: @"\\[city\\]"

  2. Regex.Replace添加忽略大小写RegexOptions.IgnoreCase的选项

  3. 对于“包含”,它不使用正则表达式。 请改用Regex.IsMatch

所以这会将你的问题中的代码变成这样:

var text = textbox.Text;
var pattern = @"\[City\]";

// Will match [city], [cITy], [CITY], but not exactly [City] 
if (Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase) && !Regex.IsMatch(text, pattern))
{
    text = Regex.Replace(text, pattern, "[City]", RegexOptions.IgnoreCase);

    // same code after that 
}

您需要对括号进行转义,使用Regex.IsMatch而不是Contains ,并使模式区分大小写。 您可以在 regex 模式中执行此操作,但 C# 内置了RegexOptions因此您可以IgnoreCase 这是它的样子:

if(Regex.IsMatch(text, @"\[city\]", RegexOptions.IgnoreCase))
{
    text = Regex.Replace(text, @"\[city\]", "[City]", RegexOptions.IgnoreCase);
}

这是一个dotnetfiddle

您需要对正则表达式中的括号等特殊字符进行转义,您可以在下面的模式字符串中看到这些字符。 然后,您需要添加正则表达式选项 RegexOptions.IgnoreCase 以在将字符串与模式字符串进行比较时忽略大小写。

        var testText = @"[CIty] [ciTY] [city] [CITy] [City]";
        Console.WriteLine("Original text: " + testText);

        var pattern = @"\[City\]";

        if(Regex.IsMatch(testText, pattern, RegexOptions.IgnoreCase))
        {
            //use the below updated value as you wish
            var updatedStringVal = Regex.Replace(testText, pattern, "[City]", RegexOptions.IgnoreCase);
            Console.WriteLine("Updated text: " + updatedStringVal);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM