Prashant Mehta
Prashant Mehta

Reputation: 482

Regular Expression in C# and Javascript

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

Answers (3)

hwnd
hwnd

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

Paul Karlin
Paul Karlin

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

Mahesh
Mahesh

Reputation: 8892

You can try this,

^[0-9!@#$%^&~*()_+\-=\[\]{};':"\\|,.<>\/?]*$

Here is working example

Upvotes: 1

Related Questions