Jigar Jain
Jigar Jain

Reputation: 1447

Regex to certain special characters

Currently i have this following regex which i use to validate the name of a company/industry and its working fine

  /(?=[a-zA-Z0-9-]{5,25}$)^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/

The above regex doesnt supports for special characters like & - . _ which are valid in my case

I came up with this but it wasnt working as expected.

 /(?=[a-zA-Z0-9-\&\_\.]{5,25}$)^[a-zA-Z0-9\&\_\.]+(-[a-zA-Z0-9\&\_\.]+)*$/

Can someone point it out where my above regex goes wrong. Also a short explaination of the above regex wud be greatly appreciated Thanks

Upvotes: 2

Views: 574

Answers (2)

CobaltBabyBear
CobaltBabyBear

Reputation: 2218

If I'm not wrong, you don't actually have to put backslash with every special character unless the special character is the backslash itself or the character -. So your regular expression would be

/(?=[a-zA-Z0-9-&_.]{5,25}$)^[a-zA-Z0-9&_.]+(-[a-zA-Z0-9&_.]+)*$/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

I don't think you have to escape & with \&, same way _ also

/(?=[a-zA-Z0-9-&_\.]{5,25}$)^[a-zA-Z0-9&_\.]+(-[a-zA-Z0-9&_\.]+)*$/

Upvotes: 3

Related Questions