Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex - alphanumeric, allowing leading whitespace but not blank string

Tags:

java

string

regex

I've been trying to make a java regex that allows only alphanumeric characters, which can have white spaces, BUT the whole string cannot be blank...

Few examples..

" hello world123" //fine
"hello123world" //fine
"hello123world " //fine
"    " //not allowed

So far I've gotten ^[a-zA-Z0-9][a-zA-Z0-9\s]*$ though this does not allow any leading whitespace and so any string with x number leading whitespace is not being matched.

Any ideas what I could add to the expression to allow leading whitespace?

like image 743
deanmau5 Avatar asked Dec 26 '22 02:12

deanmau5


1 Answers

How about just ^\s*[\da-zA-Z][\da-zA-Z\s]*$. 0 or more spaces at start, follow by at least 1 digit or letter followed by digits/letters/spaces.

Note: I did not use \w because \w includes "_", which is not alphanumeric.

Edit: Just tested all your cases on regexpal, and all worked as expected. This regex seems like the simplest one.

like image 183
David says Reinstate Monica Avatar answered Jan 17 '23 21:01

David says Reinstate Monica