开发者

'-' not working while using Regular Expressions to match special characters, c#

开发者 https://www.devze.com 2023-02-13 11:27 出处:网络
Pattern is Regex splRegExp =开发者_StackOverflow中文版 new System.Text.RegularExpressions.Regex(@\"[\\,@,+,\\,?,\\d,%,.,?,*,&,^,$,(,!,),#,-,_]\");

Pattern is

Regex splRegExp =开发者_StackOverflow中文版 new System.Text.RegularExpressions.Regex(@"[\,@,+,\,?,\d,%,.,?,*,&,^,$,(,!,),#,-,_]");

All characters work except '-'. Please advise.


Use

@"[,@+\\?\d%.*&^$(!)#_-]"

No need for all those commas.

If you place a - inside a character class, it means a literal dash only if it's at the start or end of the class. Otherwise it denotes a range like A-Z. As Damien put it, the range ,-, is indeed rather small (and doesn't contain the -, of course).


'-' has to be the first charater in your regex.

Regex splRegExp = new System.Text.RegularExpressions.Regex(@"[-,\,@,+,\,?,\d,%,.,?,*,&,^,$,(,!,),#,_]");


You need to escape the -character for it to work (it's a regular expression syntax)

Try this:

"[\,@,+,\,?,\d,%,.,?,*,&,^,$,(,!,),#,\-,_]"
0

精彩评论

暂无评论...
验证码 换一张
取 消