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
  • 161,100
  • 35
  • 287
  • 281
javing
  • 11,899
  • 31
  • 135
  • 206
  • 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
  • 45,106
  • 10
  • 73
  • 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
  • 28,017
  • 21
  • 79
  • 123
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,278
  • 7
  • 30
  • 42
1

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

pavium
  • 14,290
  • 4
  • 30
  • 46
Mahesh KP
  • 5,900
  • 12
  • 48
  • 70
1

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

^(\w+ )+\w+|\w+$
Gursel Koca
  • 20,440
  • 1
  • 23
  • 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
  • 61,566
  • 21
  • 152
  • 187