1

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?

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
javing
  • 12,307
  • 35
  • 138
  • 211
  • I did it: This is the pattern i used: `^([a-zA-Z0-9]+[a-zA-Z0-9 ]+$)?` At the end i use ? when the fields needs to be optional. Thanks for your answers. – javing Apr 22 '11 at 09:28

6 Answers6

7

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).

darioo
  • 46,442
  • 10
  • 75
  • 103
  • This allows _any_ char (other than a space) as the first char, (e.g. any of these: `@&^$@*&^$#)(@#*$`) Probably not what you want! – ridgerunner Apr 22 '11 at 07:47
  • @ridgerunner: you're correct; I updated my answer. I'd say this is the most readable version for use – darioo Apr 22 '11 at 08:04
3

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 ]+$

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
2

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.

Arnab Das
  • 3,548
  • 8
  • 31
  • 43
1

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

pavium
  • 14,808
  • 4
  • 33
  • 50
Mahesh KP
  • 6,248
  • 13
  • 50
  • 71
1

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

^(\w+ )+\w+|\w+$
Gursel Koca
  • 20,940
  • 2
  • 24
  • 34
1

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"

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192