简体   繁体   English

String.Replace的替代品

[英]Alternative to String.Replace

So I was writing some code today that basically looks like this: 所以今天我写的代码基本上是这样的:

string returnString = s.Replace("!", " ")
            .Replace("@", " ")
            .Replace("#", " ")
            .Replace("$", " ")
            .Replace("%", " ")
            .Replace("^", " ")
            .Replace("*", " ")
            .Replace("_", " ")
            .Replace("+", " ")
            .Replace("=", " ")
            .Replace("\", " ")

Which isn't really nice. 这不是很好。 I was wondering if there's a regex or something that I could write that would replace all the calls to the Replace() function? 我想知道是否有正则表达式或我可以写的东西会替换所有对Replace()函数的调用?

You can use Regex.Replace() . 您可以使用Regex.Replace() All of the characters can be placed between square brackets, which matches any character between the square brackets. 所有字符都可以放在方括号之间,方括号与方括号之间的任何字符匹配。 Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. 一些特殊字符必须用反斜杠转义,我在这里使用@verbatim字符串,所以我不必为C#编译器双重转义它们。 The first parameter is the input string and the last parameter is the replacement string. 第一个参数是输入字符串,最后一个参数是替换字符串。

var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," ");

FYI - if you need to modify this regex, you'll need to have an understanding of the regular expression language. 仅供参考 - 如果您需要修改此正则表达式,则需要了解正则表达式语言。 It is quite simple, and as a developer you really owe it to yourself to add regular expressions to your toolbox - you don't need them every day, but being able to apply them appropriately where necessary when the need does arise will pay you back tenfold for the initial effort. 这很简单,作为开发人员,你真的应该为自己添加正则表达式到你的工具箱 - 你不需要每天都有它们,但是在需要的时候能够适当地应用它们会让你回来最初努力的十倍。 Here is a link to a website with some top notch, easy to follow tutorials and reference material on regular expressions: regular-expressions.info . 这是一个链接到一个网站,其中包含一些顶尖的,易于学习的关于正则表达式的教程和参考资料: regular-expressions.info Once you get a feel for regular expressions and want to use them in your software, you'll want to buy Regex Buddy. 一旦你对正则表达式有所了解并希望在你的软件中使用它们,你就会想要购买Regex Buddy。 It is a cheap and extraordinary tool for learning and using regular expressions. 它是学习和使用正则表达式的廉价而非凡的工具。 I very rarely purchase development tools, but this one was worth every penny. 很少购买开发工具,但是这一次是值得每一分钱。 It is here: Regex Buddy 它在这里: Regex Buddy

s/[!@#$%^*_+=\]/ /

Would be the regex for it... in c# you should be able to use 将是它的正则表达式...在c#中你应该可以使用

Regex.Replace(yourstring, "[!@#$%^*_+=\]", "" ); 

Though my C# is rusty.. 虽然我的C#生锈了..

If you don't care to delve into Regex, here are a couple of other extension-method possibilities. 如果你不想深入研究正则表达式,这里有一些其他的扩展方法可能性。

You can pass in the specific characters you want to replace: 您可以传入要替换的特定字符:

static public string ReplaceCharsWithSpace(this string original, string chars)
{
    var result = new StringBuilder();
    foreach (var ch in original)
    {
        result.Append(chars.Contains(ch) ? ' ' : ch);
    }
    return result.ToString();
}

Or if you know you want to only keep or only strip out specific types of characters, you can use the various methods in char , such as IsLetter , IsDigit , IsPunctuation , and IsSymbol : 或者,如果您知道只想保留或仅删除特定类型的字符,则可以使用char的各种方法,例如IsLetterIsDigitIsPunctuationIsSymbol

static public string ReplaceNonLetterCharsWithSpace(this string original)
{
    var result = new StringBuilder();
    foreach (var ch in original)
    {
        result.Append(char.IsLetter(ch) ? ch : ' ');
    }
    return result.ToString();
}

Here's how you'd use each of these possibilities: 以下是您如何使用这些可能性:

string s = "ab!2c";
s = s.ReplaceCharsWithSpace(@"!@#$%^*_+=/");  // s contains "ab  c"

string t = "ab3*c";
t = t.ReplaceNonLetterCharsWithSpace();  // t contains "ab  c"

Maybe you can reduce this down to a couple of lines, if desired, by using a Lambda expression and List<>, ForEach 如果需要,您可以使用Lambda表达式和List<>, ForEach将其减少到几行

using System.Collections.Generic;

namespace ReplaceWithSpace 
 {
    class Program 
    {
        static void Main(string[] args) 
        {
            string someString = "#1, 1+1=2 $string$!";

            var charsToRemove = new List<char>(@"!@#$%^*_+=\");
            charsToRemove.ForEach(c => someString = someString.Replace(c, ' '));

            System.Diagnostics.Debug.Print(someString); //" 1, 1 1 2  string  "
        }
    }

}

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

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