javing
javing

Reputation: 12423

Blank spaces in regular expression

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

Answers (6)

darioo
darioo

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

Lekensteyn
Lekensteyn

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

Gursel Koca
Gursel Koca

Reputation: 21300

This regex dont allow spaces at the end of string, one downside it accepts underscore character also.

^(\w+ )+\w+|\w+$

Upvotes: 1

Oscar Mederos
Oscar Mederos

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

Arnab Das
Arnab Das

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

Mahesh KP
Mahesh KP

Reputation: 6446

try like this ^[a-zA-Z0-9 ]+$ that is, add a space in it

Upvotes: 1

Related Questions