如何替换所有给定的字符? [英] How to replace all given characters?

查看:52
本文介绍了如何替换所有给定的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一种方法,该方法使用 replacementCharacter 使用 replacementCharacter 来替换输入数组( charsToReplace )中所有出现的字符正则表达式.如果数组包含可能更改的正则表达式模式含义的字符,例如']',则我写的版本不起作用'^'.

I'm trying to write a method that replaces all occurrences of the characters in the input array (charsToReplace) with the replacementCharacter using regex. The version I have written does not work if the array contains any characters that may change the meaning of the regex pattern, such as ']' or '^'.

public static string ReplaceAll(string str, char[] charsToReplace, char replacementCharacter)
{
    if(str.IsNullOrEmpty())
    {
        return string.Empty;
    }

    var pattern = $"[{new string(charsToReplace)}]";
    return Regex.Replace(str, pattern, replacementCharacter.ToString());
}

因此 ReplaceAll("/] a",{'/',']'},'a')应该返回"aaa" .

推荐答案

在字符类中,仅4个字符需要转义, ^ -] \ .您不能使用 Regex.Escape 仅应用于 字符类之外的文字字符(序列).

Inside a character class, only 4 chars require escaping, ^, -, ] and \. You can't use Regex.Escape because it does not escape -and ] as they are not "special" outside a character class. Note that Regex.Escape is meant to be used only for literal char (sequences) that are outside character classes.

一个未转义的] char将过早关闭您的角色类,这是您的代码无法正常工作的主要原因.

An unescaped ] char will close your character class prematurely and that is the main reason why your code does not work.

因此,固定的 pattern 变量定义看起来像

So, the fixed pattern variable definition can look like

var pattern = $"[{string.Concat(charsToReplace).Replace(@"\", @"\\").Replace("-", @"\-").Replace("^", @"\^").Replace("]", @"\]")}]";

请参见在线C#演示.

这篇关于如何替换所有给定的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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