简体   繁体   English

正则表达式问题c#数字现在是下划线

[英]regex issue c# numbers are underscores now

My Regex is removing all numeric (0-9) in my string. 我的正则表达式删除了我的字符串中的所有数字(0-9)。 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 = . 问题是你的模式在中间使用了一个破折号,它起到了from )=的ascii字符的范围。 Here's a breakdown: 这是一个细分:

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

As you can see, numbers start at 49, and falls between the range of 41-61, so they're matched and replaced. 如你所见,数字从49开始,介于41-61之间,因此它们匹配并被替换。

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. 我没有使用C#,但通常“*”字符也是需要转义的控制字符。

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”字符:

A*

The "Owl" book from oreilly is what you really need to research this: 来自oreilly的“猫头鹰”一书是您真正需要研究的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM