Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special characters Regex

Hello I'm try to remove special characters from user inputs.

        public void fd()
        {
            string output = "";
            string input = Console.ReadLine();
            char[] charArray = input.ToCharArray();

            foreach (var item in charArray)
            {

                if (!Char.IsLetterOrDigit(item))
                {

                   \\\CODE HERE                    }

            }

            output = new string(trimmedChars);
            Console.WriteLine(output);
        }

At the end I'm turning it back to a string. My code only removes one special character in the string. Does anyone have any suggestions on a easier way instead

like image 810
Calvin Jones Avatar asked Nov 13 '13 04:11

Calvin Jones


People also ask

How do I allow only special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.

What is the meaning of +$ in regex?

The usual context of wildcard characters is in globbing similar names in a list of files, whereas regexes are usually employed in applications that pattern-match text strings in general. For example, the regex ^[ \t]+|[ \t]+$ matches excess whitespace at the beginning or end of a line.

How do you skip special characters in regex?

The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters. Use a double backslash ( \\ ) to denote an escaped string literal.

Are brackets special characters in regex?

The special characters are: a. ., *, [, and \ (period, asterisk, left square bracket, and backslash, respectively), which are always special, except when they appear within square brackets ([]; see 1.4 below). c. $ (dollar sign), which is special at the end of an entire RE (see 4.2 below).


1 Answers

You have a nice implementation, just consider using next code, which is only a bit shorter, but has a little bit higher abstractions

var input =  " th@ere's! ";

Func<char, bool> isSpecialChar = ch => !char.IsLetter(ch) && !char.IsDigit(ch);

for (int i = 1; i < input.Length - 1; i++)
{
    //if current character is a special symbol
    if(isSpecialChar(input[i])) 
    {
        //if previous or next character are special symbols
        if(isSpecialChar(input[i-1]) || isSpecialChar(input[i+1]))
        {
            //remove that character
            input = input.Remove(i, 1);
            //decrease counter, since we removed one char
            i--;
        }
    }
}
Console.WriteLine(input); //prints " th@ere's "

A new string would be created each time you would call Remove. Use a StringBuilder for a more memory-performant solution.

like image 173
Ilya Ivanov Avatar answered Oct 27 '22 07:10

Ilya Ivanov