5

我的正则表达式正在删除字符串中的所有数字 (0-9)。我不明白为什么所有数字都被替换为_

编辑:我知道我的“_”正则表达式模式将字符更改为下划线。但不是为什么数字!

谁能帮我吗?我只需要像所有特殊字符一样删除。

在此处查看正则表达式:

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

Output: "input here ________"
4

5 回答 5

8

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:

"[-!@#$%^&*()=+`~{}'|]"
于 2012-12-20T13:57:01.637 回答
4

you must escape - because sequence [)-=] contains digits

string symbolPattern = "[!@#$%^&*()\-=+`~{}'|]";
于 2012-12-20T13:56:11.273 回答
2

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.

于 2012-12-20T13:57:31.793 回答
1

你需要在你的正则表达式中转义你的特殊字符。例如,* 是通配符匹配。看看其中一些特殊字符对您的比赛意味着什么。

于 2012-12-20T13:54:38.910 回答
0

我没有使用 C#,但通常“*”字符也是需要转义的控制字符。

以下匹配一整行任何字符,尽管“^”和“$”有些多余:

^.*$

这匹配出现在字符串中的任意数量的“A”字符:

A*

来自 oreilly 的“猫头鹰”书是您真正需要研究的:

http://shop.oreilly.com/product/9780596528126.do?green=B5B9A1A7-B828-5E41-9D38-70AF661901B8&intcmp=af-mybuy-9780596528126.IP

于 2012-12-20T14:15:28.287 回答