仅用 1 个空格替换非字母数字字符和多个空格

问题描述 投票:0回答:4

我正在尝试用 1 个空格替换所有“非字母数字字符”和“多个空格”

我有 2 个可行的解决方案,但是我想知道是否可以有效地将它们组合起来?

给定

var str = "ASD S-DF 2134 4@# 4    234234 #$)(u SD";
var options = RegexOptions.None;

非字母数字字符的解决方案

var rgxAlpha = new Regex("[^a-zA-Z0-9]");
str = rgxAlpha.Replace(str, " ", options);

解决方案多个空间

var regexSpace = new Regex(@"[ ]{2,}", options);
str = regexSpace.Replace(str, " ");

预期结果

ASD S DF 2134 4 4 234234 u SD
c# regex
4个回答
7
投票

只需下面的内容就足够了,因为

[^a-zA-Z0-9]+
也匹配空格,因此您不需要显式添加
[ ]{2,}

string result = Regex.Replace(str, @"[^a-zA-Z0-9]+", " ");

演示


2
投票

假设它们都有效:

var rgxPattern = new Regex(@"[^a-zA-Z0-9]+|[ ]{2,}");

只需添加一个 |他们之间。


0
投票
    string szOut= "";
    char previous;
    foreach (char cr in str.ToCharArray())
    {
            if(cr == ' '&& previous == ' ')
                continue;

            if (IsAlphaNumeric(cr))
                szOut+= cr;

            previous = cr;
    }       
    return szOut;

....

    public static Boolean IsAlphaNumeric(char cr)
    {
        return char.IsLetter(cr) || char.IsNumber(cr) || cr == ' ';
    }

0
投票
/// <summary> Alphanumeric characters are appended to result string.
/// One or more non-alphanumeric characters are replaced by ONE "replacement" character.
/// </summary>
static private string ReplaceNonAlphaNumeric(string str, char replacement = ' ')
{
    var sb = new System.Text.StringBuilder();

    // True when last character was replaced by "replacement" character.
    bool replacing = false;
    foreach (char cr in str)
    {
        if (char.IsLetterOrDigit(cr))
        {
            sb.Append(cr);
            replacing = false;
        }
        else
        {   // blank or other non-alphanumeric.
            if (replacing)
                continue;   // Only output one "replacement" character.

            sb.Append(replacement);
            replacing = true;
        }
    }
    return sb.ToString();
}

用途:

ReplaceNonAlphaNumeric(yourString)

示例:

"a1b23c456" => "a1b23c456"
"a1   b23c 456" => "a1 b23c 456"
"a1-b23c! ?#456" => "a1 b23c 456"

或:

ReplaceNonAlphaNumeric(yourString, '-')

"a1   b23c 456" => "a1-b23c-456"
"a1-b23c! ?#456" => "a1-b23c-456"
© www.soinside.com 2019 - 2024. All rights reserved.