c# - How to replace all given characters?
问题描述
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());
}
So ReplaceAll("/]a", {'/', ']' }, 'a')
should return "aaa"
.
解决方案
我建议使用Linq,而不是常规表达式:
using System.Linq;
...
public static string ReplaceAll(
string str, char[] charsToReplace, char replacementCharacter)
{
// Please, note IsNullOrEmpty syntax
// we should validate charsToReplace as well
if (string.IsNullOrEmpty(str) || null == charsToReplace || charsToReplace.Length <= 0)
return str; // let's just do nothing (say, not turn null into empty string)
return string.Concat(str.Select(c => charsToReplace.Contains(c)
? replacementCharacter
: c));
}
如果你坚持Regex
(注意,我们应该Regex.Escape
在 chars 内charsToReplace
)。但是,根据手册 Regex.Escape
并没有转义 -
,并且在正则表达式括号[
内具有特殊含义。
public static string ReplaceAll(
string str, char[] charsToReplace, char replacementCharacter) {
if (string.IsNullOrEmpty(str) || null == charsToReplace || charsToReplace.Length <= 0)
return str;
string charsSet = string.Concat(charsToReplace
.Select(c => new char[] { ']', '-' }.Contains(c) // in case of '-' and ']'
? $@"\{c}" // escape them as well
: Regex.Escape(c.ToString())));
return Regex.Replace(
str,
$"[{charsSet}]+",
m => new string(replacementCharacter, m.Length));
}
推荐阅读
- javascript - [PHP cURL]:会话 cookie 未保存?
- xamarin.forms - Xamarin Android UI 自动化与适用于 Android 的 UIAutomator2 驱动程序
- go - 在 Revel 中从 ViewArg 中选择模板
- hazelcast - hazelcast 中的 hazelcast.operation.thread.count 和 hazelcast.operation.generic.thread.count 有什么区别?
- logic - 了解 NuSMV 中递归定义的错误
- python - 在 Python 中实现正规方程的问题
- python - 独立于 Web 服务器的 dogpile 内存后端
- python - 用 numpy 数组与 DataFrame 屏蔽 pandas DataFrame
- wordpress - WordPress 的 wp_get_attachment_image_srcset 未返回所有图像 srcset 大小
- pycharm - 使用“查找用法”命令查找外部用法?