Tsundoku
Tsundoku

Reputation: 9428

How do I disallow numbers in a regular expression?

Hello I was writing a Regular Expression (first time in my life I might add) but I just can't figure out how to do what I want. So far, so good since I already allow only Letters and spaces (as long as it's not the first character) now what I'm missing is that I don't want to allow any numbers in between the characters...could anybody help me please?

/^[^\s][\sa-zA-Z]+[^\d\W]/

Upvotes: 1

Views: 3920

Answers (3)

Alan Moore
Alan Moore

Reputation: 75272

If you want to ensure that spaces occur only between words, use this:

/^[A-Za-z]+(?:\s+[A-Za-z]+)*$/

Upvotes: 1

Graeme Perrow
Graeme Perrow

Reputation: 57278

If you only want to allow letters and spaces, then what you have is almost correct:

/^[a-zA-Z][\sa-zA-Z]*$/

The $ at the end signifies the end of the string.

Edited to correct answer, thanks to @Alnitak

Upvotes: 1

Alnitak
Alnitak

Reputation: 340055

OK, what you need is:

/^[a-zA-Z][\sa-zA-Z]*$/

This matches:

^           - start of line
[a-zA-Z]    - any letter
[\sa-zA-Z]* - zero or more letters or spaces
$           - the end of the line

If you want to ensure that it also ends in a letter then put another

[a-zA-Z]

before the $. Note however that the string will then have to contain at least two letters (one at each end) to match.

Upvotes: 5

Related Questions