Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex issue c# numbers are underscores now

Tags:

c#

regex

My Regex is removing all numeric (0-9) in my string. I don't get why all numbers are replaced by _

EDIT: I understand that my "_" regex pattern changes the characters into underscores. But not why numbers!

Can anyone help me out? I only need to remove like all special characters.

See regex here:

 string symbolPattern = "[!@#$%^&*()-=+`~{}'|]";
Regex.Replace("input here 12341234" , symbolPattern, "_");

Output: "input here ________"
like image 373
Rob Avatar asked Dec 20 '12 13:12

Rob


People also ask

Can regex be used in C?

It is used in every programming language like C++, Java, and Python. Used to find any of the characters or numbers specified between the brackets.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What is Regmatch_t?

The regmatch_t elements correspond to subexpressions positionally; the first element (index 1 ) records where the first subexpression matched, the second element records the second subexpression, and so on. The order of the subexpressions is the order in which they begin.

How do you write regex code?

Writing a regular expression pattern. A regular expression pattern is composed of simple characters, such as /abc/ , or a combination of simple and special characters, such as /ab*c/ or /Chapter (\d+)\.\d*/ . The last example includes parentheses, which are used as a memory device.


1 Answers

The problem is your pattern uses a dash in the middle, which acts as a range of the ascii characters from ) to =. Here's a breakdown:

  • ): 41
  • 1: 49
  • =: 61

As you can see, numbers start at 49, and falls between the range of 41-61, so they're matched and replaced.

You need to place the - at either the beginning or end of the character class for it to be matched literally rather than act as a range:

"[-!@#$%^&*()=+`~{}'|]"
like image 85
Ahmad Mageed Avatar answered Sep 23 '22 00:09

Ahmad Mageed