Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for allowing only certain special characters and also including the alphanumerical characters

Tags:

java

regex

I'm struggling with REGEX and require it for a program.

The input require only alphanumerical keys and also (allow only comma,:,space,/,- in special chars)

I have tried = (^[a-zA-Z0-9,:\S/-]*$) As far as i understand and please correct me if I'm wrong. a-zA-Z0-9 - The alphanumerical keys. ,: - Comma and colon \S - Space / - I'm not sure how to represent a forward slash thus i escaped it - - Dash also not sure if it is needed to escape it.

Would be appreciated if this can be corrected and also a explanation of each part.

Thanks in advance.

like image 875
Tinus Jackson Avatar asked Oct 19 '15 05:10

Tinus Jackson


People also ask

How do I allow only special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.

How do you write alphanumeric in regex?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.

What is alphanumeric and special characters?

An alphanumeric password contains numbers, letters, and special characters (like an ampersand or hashtag). In theory, alphanumeric passwords are harder to crack than those containing just letters. But they can also be harder to both create and remember.


1 Answers

You can replace a-zA-Z0-9 with just \\w which is short for [a-zA-Z_0-9]. Furthermore, \\S is any character, but not a whitespace, you should use a \\s instead. You don't need to escape /, and even - if it's the first one or the last one, because if it's placed between two characters it could be interpreted as range and you'll have to escape it. So, you can make your regex like ^([\w,:\s/-]*)$

like image 129
Stanislav Avatar answered Oct 25 '22 03:10

Stanislav