regex issue c# numbers are underscores now



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 ________"





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:



[], []

Facebook Comments

Post a comment