Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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.

like image 512
codenamepenryn Avatar asked Apr 10 '14 22:04

codenamepenryn


People also ask

What is the regular expression matching one or more specific characters?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .

What does \\ s+ mean in regex?

The plus sign + is a greedy quantifier, which means one or more times. For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What is the regular expression for string?

A regular expression (regex) defines a search pattern for strings. The search pattern can be anything from a simple character, a fixed string or a complex expression containing special characters describing the pattern.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


1 Answers

.*[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

like image 61
amit Avatar answered Oct 13 '22 11:10

amit