SRA
SRA

Reputation: 1691

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

Pattern is

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

All characters work except '-'. Please advise.

Upvotes: 0

Views: 435

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

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).

Upvotes: 4

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

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

Try this:

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

Upvotes: 0

Xavinou
Xavinou

Reputation: 802

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

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

Upvotes: 1

Related Questions