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:
"[-!@#$%^&*()=+`~{}'|]"
你必须逃避-
因为sequence [)-=]
包含数字
string symbolPattern = "[!@#$%^&*()\-=+`~{}'|]";
Move the -
to the end of the list so it is seen as a literal:
"[!@#$%^&*()=+`~{}'|-]"
Or, to the front :
"[-!@#$%^&*()=+`~{}'|]"
As it stands, it will match all characters in the range )-=
, which includes all numerals.
You need to escape your special characters in your regex. For instance, * is a wildcard match. Look at what some of those special characters mean for your match.
I've not used C#, but typically the "*" character is also a control character that would need escaping.
The following matches a whole line of any characters, although the "^" and "$" are some what redundant:
^.*$
This matches any number of "A" characters that appear in a string:
A*
The "Owl" book from oreilly is what you really need to research this:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.