Reputation: 12423
I use this regular to validate many of the input fields of my java web app:
"^[a-zA-Z0-9]+$"
But i need to modify it, because i have a couple of fields that need to allow blank spaces(for example: Address).
How can i modify it to allow blank spaces(if possible not at the start).
I think i need to use some scape character like \
I tried a few different combinations but none of them worked. Can somebody help me with this regex?
Upvotes: 1
Views: 22745
Reputation: 47183
I'd suggest using this:
^[a-zA-Z0-9][a-zA-Z0-9 ]+$
It adds two things: first, you're guaranteed not to have a space at the beginning, while allowing characters you need. Afterwards, letters a-z
and A-Z
are allowed, as well as all digits and spaces (there's a space at the end of my regex).
Upvotes: 7
Reputation: 66425
Try this one: I assume that any input with a length of at least one character is valid. The previously mentioned answers does not take that into account.
"^[a-zA-Z0-9][a-zA-Z0-9 ]*$"
If you want to allow all whitespace characters, replace the space by "\s"
Upvotes: 1
Reputation: 21300
This regex dont allow spaces at the end of string, one downside it accepts underscore character also.
^(\w+ )+\w+|\w+$
Upvotes: 1
Reputation: 29833
If you want to use only a whitespace, you can do:
^[a-zA-Z0-9 ]+$
If you want to include tabs \t
, new-line \n
\r\n
characters, you can do:
^[a-zA-Z0-9\s]+$
Also, as you asked, if you don't want the whitespace to be at the begining:
^[a-zA-Z0-9][a-zA-Z0-9 ]+$
Upvotes: 3
Reputation: 3728
Use this: ^[a-zA-Z0-9]+[a-zA-Z0-9 ]+$
. This should work. First atom ensures that there must be at least one character at beginning.
Upvotes: 2