Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i remove none alphabet chars from a string[]? [duplicate]

Tags:

c#

regex

This is the code:

StringBuilder sb = new StringBuilder();
Regex rgx = new Regex("[^a-zA-Z0-9 -]");

var words = Regex.Split(textBox1.Text, @"(?=(?<=[^\s])\s+\w)");
for (int i = 0; i < words.Length; i++)
{
    words[i] = rgx.Replace(words[i], "");
}

When im doing the Regex.Split() the words contain also strings with chars inside for exmaple:

Daniel>

or

Hello:

or

\r\nNew

or

hello---------------------------

And i need to get only the words without all the signs

So i tried to use this loop but i end that in words there are many places with "" And some places with only ------------------------

And i cant use this as strings later in my code.

like image 539
Haim Kashi Avatar asked Dec 08 '22 14:12

Haim Kashi


1 Answers

You don't need a regex to clear non-letters. This will remove all non-unicode letters.

public string RemoveNonUnicodeLetters(string input)
{
    StringBuilder sb = new StringBuilder();
    foreach(char c in input)
    {
        if(Char.IsLetter(c))
           sb.Append(c);
    }

    return sb.ToString();
}

Alternatively, if you only want to allow Latin letters, you can use this

public string RemoveNonLatinLetters(string input)
{
    StringBuilder sb = new StringBuilder();
    foreach(char c in input)
    {
        if(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
           sb.Append(c);
    }

    return sb.ToString();
}

Benchmark vs Regex

public static string RemoveNonUnicodeLetters(string input)
{
       StringBuilder sb = new StringBuilder();
       foreach (char c in input)
       {
            if (Char.IsLetter(c))
                sb.Append(c);
       }

            return sb.ToString();
}



static readonly Regex nonUnicodeRx = new Regex("\\P{L}");

public static string RemoveNonUnicodeLetters2(string input)
{
     return nonUnicodeRx.Replace(input, "");
}


static void Main(string[] args)
{

    Stopwatch sw = new Stopwatch();

    StringBuilder sb = new StringBuilder();


    //generate guids as input
    for (int j = 0; j < 1000; j++)
    {
        sb.Append(Guid.NewGuid().ToString());
    }

    string input = sb.ToString();

    sw.Start();

    for (int i = 0; i < 1000; i++)
    {
        RemoveNonUnicodeLetters(input);
    }

    sw.Stop();
    Console.WriteLine("SM: " + sw.ElapsedMilliseconds);

    sw.Restart();
    for (int i = 0; i < 1000; i++)
    {
        RemoveNonUnicodeLetters2(input);
    }

    sw.Stop();
    Console.WriteLine("RX: " + sw.ElapsedMilliseconds);


}

Output (SM = String Manipulation, RX = Regex)

SM: 581
RX: 9882

SM: 545
RX: 9557

SM: 664
RX: 10196
like image 84
keyboardP Avatar answered Dec 11 '22 08:12

keyboardP