codenamepenryn
codenamepenryn

Reputation: 461

Regular Expression for a string that contains one or more letters somewhere in it

What would be a regular expression that would evaluate to true if the string has one or more letters anywhere in it.

For example:

1222a3999 would be true

a222aZaa would be true

aaaAaaaa would be true

but:

1111112())-- would be false

I tried: ^[a-zA-Z]+$ and [a-zA-Z]+ but neither work when there are any numbers and other characters in the string.

Upvotes: 7

Views: 35413

Answers (4)

amit
amit

Reputation: 178411

.*[a-zA-Z].*

The above means one letter, and before/after it - anything is fine.

In java:

String regex = ".*[a-zA-Z].*";
System.out.println("1222a3999".matches(regex));
System.out.println("a222aZaa ".matches(regex));
System.out.println("aaaAaaaa ".matches(regex));
System.out.println("1111112())-- ".matches(regex));

Will provide:

true
true
true
false

as expected

Upvotes: 17

Darren
Darren

Reputation: 11

.*[a-zA-Z]?.*

Should get you the result you want.

The period matches any character except new line, the asterisk says this should exist zero or more times. Then the pattern [a-zA-Z]? says give me at least one character that is in the brackets because of the use of the question mark. Finally the ending .* says that the alphabet characters can be followed by zero or more characters of any type.

Upvotes: 1

^.*[a-zA-Z].*$

Depending on the implementation, match() functions check if the entire string matches (which is probably why your [a-zA-Z] or [a-zA-Z]+ patterns didn't work).

Either use match() with the above pattern or use some sort of search() method instead.

Upvotes: 3

Barmar
Barmar

Reputation: 780724

This regexp should do it:

[a-zA-Z]

It matches as long as there's a single letter anywhere in the string, it doesn't care about any of the other characters.

[a-zA-Z]+

should have worked as well, I don't know why it didn't for you.

Upvotes: 2

Related Questions