如何从字符串中去除非字母数字字符(包括空格)



如何用Replace从字符串和C#中的松散空格中去除非字母数字字符?

我想保留a-z,a-z,0-9,什么都不保留(甚至不保留"空格)。

"Hello there(hello#)".Replace(regex-i-want, "");

应该给出

"Hellotherehello"

我尝试过"Hello there(hello#)".Replace(@"[^A-Za-z0-9 ]", "");,但空格仍然存在。

在您的正则表达式中,您已经排除了匹配的空格(并且您没有使用我完全忽略的Regex.Replace()…):

result = Regex.Replace("Hello there(hello#)", @"[^A-Za-z0-9]+", "");

应该起作用。+通过一次匹配多个连续的非字母数字字符而不是逐个匹配,使正则表达式更加高效。

如果您也想保留非ASCII字母/数字,请使用以下正则表达式:

@"[^p{L}p{N}]+"

离开

BonjourmesélèvesGutenMorgenliebeSchüler

而不是

BonjourmeslvesGutenMorgenliebeSchler

您可以使用Linq筛选出所需的字符:

  String source = "Hello there(hello#)";
  // "Hellotherehello"
  String result = new String(source
    .Where(ch => Char.IsLetterOrDigit(ch))
    .ToArray());

  String result = String.Concat(source
    .Where(ch => Char.IsLetterOrDigit(ch)));  

因此您不需要正则表达式

或者你也可以这样做:

    public static string RemoveNonAlphanumeric(string text)
    {
        StringBuilder sb = new StringBuilder(text.Length);
        for (int i = 0; i < text.Length; i++)
        {
            char c = text[i];
            if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
                sb.Append(text[i]);
        }
        return sb.ToString();
    }

用法:

string text = SomeClass.RemoveNonAlphanumeric("text LaLa (lol) á ñ $ 123 ٠١٢٣٤");
//text: textLaLalol123

上面犯的错误是错误地使用了Replace(它不需要正则表达式,感谢CodeInChaos)。

以下代码应执行指定的操作:

Regex reg = new Regex(@"[^p{L}p{N}]+");//Thanks to Tim Pietzcker for regex
string regexed = reg.Replace("Hello there(hello#)", "");

这给出:

regexed = "Hellotherehello"

作为替换操作作为扩展方法:

public static class StringExtensions
{
    public static string ReplaceNonAlphanumeric(this string text, char replaceChar)
    {
        StringBuilder result = new StringBuilder(text.Length);
        foreach(char c in text)
        {
            if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
                result.Append(c);
            else
                result.Append(replaceChar);
        }
        return result.ToString();
    } 
}

测试:

[TestFixture]
public sealed class StringExtensionsTests
{
    [Test]
    public void Test()
    {
        Assert.AreEqual("text_LaLa__lol________123______", "text LaLa (lol) á ñ $ 123 ٠١٢٣٤".ReplaceNonAlphanumeric('_'));
    }
}
var text = "Hello there(hello#)";
var rgx = new Regex("[^a-zA-Z0-9]");
text = rgx.Replace(text, string.Empty);

使用以下正则表达式使用regex从字符串中删除所有字符。替换

([^A-Za-z0-9s])

在.Net 4.0中,您可以使用String类的IsNullOrWhitespace方法来删除所谓的空白字符。请看这里http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx然而,正如@CodeInChaos所指出的,有很多字符可以被视为字母和数字。如果只想查找a-Za-z0-9,则可以使用正则表达式。

最新更新