更换与string.replace与Regex.Replace [英] Replace String.Replace with Regex.Replace

查看:248
本文介绍了更换与string.replace与Regex.Replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private string Check_long(string input)
{
    input = input.Replace("cool", "supercool");
    input = input.Replace("cool1", "supercool1");
    input = input.Replace("cool2", "supercool2");
    input = input.Replace("cool3", "supercool3");
    return input;
}

private string Check_short(string input)
{    
    input = Regex.Replace(input, "cool", "supercool", RegexOptions.IgnoreCase);
    input = Regex.Replace(input, "cool1", "supercool1", RegexOptions.IgnoreCase);
    input = Regex.Replace(input, "cool2", "supercool2", RegexOptions.IgnoreCase);
    input = Regex.Replace(input, "cool3", "supercool3", RegexOptions.IgnoreCase);
    return input;
}

旧的解决方案与string.replace 是工作就好了。但它不支持不区分大小写。因此,我不得不检查 Regex.Replace ,但现在它不会工作。这是为什么呢?

The old solution with String.Replace was working just fine. But it didn't support case-insensitivity. So I had to check for Regex.Replace, but now it won't work. Why is that ?

推荐答案

您新的code应该很好地工作。请注意,您也可以使用捕获组保留您输入的情况下:

Your new code should work fine. Note that you can also retain the case of your input using a capture group:

private string Check_short(string input)
{    
    return Regex.Replace(input, "(cool)", "super$1", RegexOptions.IgnoreCase);
}

这篇关于更换与string.replace与Regex.Replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆