Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to accept only alphabets and spaces and disallowing spaces at the beginning and the end of the string

Tags:

java

regex

I have the following requirements for validating an input field:

  1. It should only contain alphabets and spaces between the alphabets.
  2. It cannot contain spaces at the beginning or end of the string.
  3. It cannot contain any other special character.

I am using following regex for this:

^(?!\s*$)[-a-zA-Z ]*$

But this is allowing spaces at the beginning. Any help is appreciated.

like image 943
gauravdott Avatar asked May 22 '12 08:05

gauravdott


1 Answers

For me the only logical way to do this is:

^\p{L}+(?: \p{L}+)*$

At the start of the string there must be at least one letter. (I replaced your [a-zA-Z] by the Unicode code property for letters \p{L}). Then there can be a space followed by at least one letter, this part can be repeated.

\p{L}: any kind of letter from any language. See regular-expressions.info

The problem in your expression ^(?!\s*$) is, that lookahead will fail, if there is only whitespace till the end of the string. If you want to disallow leading whitespace, just remove the end of string anchor inside the lookahead ==> ^(?!\s)[-a-zA-Z ]*$. But this still allows the string to end with whitespace. To avoid this look back at the end of the string ^(?!\s)[-a-zA-Z ]*(?<!\s)$. But I think for this task a look around is not needed.

like image 50
stema Avatar answered Oct 20 '22 19:10

stema