Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for alphabets with spaces

I need help with regular expression. I need a expression which allows only alphabets with space for ex. college name.

I am using :

var regex = /^[a-zA-Z][a-zA-Z\\s]+$/; 

but it's not working.

like image 491
Nitin Kabra Avatar asked Feb 15 '12 07:02

Nitin Kabra


People also ask

Can regular expressions have spaces?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

How do you put a space in a regular expression?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

How do you check if a string contains only alphabets and space?

In order to check if a String has only unicode letters in Java, we use the isDigit() and charAt() methods with decision making statements. The isLetter(int codePoint) method determines whether the specific character (Unicode codePoint) is a letter.

What is the regular expression for characters?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.


2 Answers

Just add the space to the [ ] :

var regex = /^[a-zA-Z ]*$/; 
like image 80
Petar Ivanov Avatar answered Oct 07 '22 07:10

Petar Ivanov


This is the better solution as it forces the input to start with an alphabetic character. The accepted answer is buggy as it does not force the input to start with an alphabetic character.

[a-zA-Z][a-zA-Z ]+ 
like image 28
Sunil Kumar B M Avatar answered Oct 07 '22 06:10

Sunil Kumar B M