Reputation: 482
I want to implement regular express for below condition , can any one help please
Numeric 0-9 with special character/ \ @ # $ % ^ & * ! - ~ . _ ( ) & space allowed
like : 123abc not allowed
like : 123#$%~. are allowed
Upvotes: 0
Views: 607
Reputation: 70722
You've pretty much wrote the regular expression yourself, you need to add those characters to a character class with proper escaping, use a quantifier and anchor your expression.
^[0-9/\\@#$%^&*!~._() -]+$
In C#, you can use the Regex.IsMatch()
method to validate:
if (Regex.IsMatch(input, @"^[0-9/\\@#$%^&*!~._() -]+$")) { ... }
In JS, you can use the test()
method to validate:
var re = /^[0-9/\\@#$%^&*!~._() -]+$/
if (re.test(input)) { ... }
Upvotes: 5
Reputation: 840
For the regex itself, you should be able to pretty much list the allowed characters in square brackets:
^[0-9/\\@#$%^&*!-~._()\ ]*$
Use * at the end (before the trailing $) to match 0 or more characters (i.e. if empty string is OK), or use + at the end (before the trailing $) to match 1 or more characters.
Depending on the language / regex implementation, you might need to escape more of those characters within the pattern string.
Upvotes: 1