Jignesh Ansodariya
Jignesh Ansodariya

Reputation: 12695

How to check whether a string contains at least one alphabet in java?

I want such a validation that My String must be contains at least one alphabet.

I am using the following:

String s = "111a11";
boolean flag = s.matches("%[a-zA-Z]%");

flag gives me false even though a is in my string s

Upvotes: 40

Views: 112950

Answers (3)

Muhammad Etisam Zafar
Muhammad Etisam Zafar

Reputation: 452

In kotlin

val inputString = "Hello123"
val containsAlphabets = inputString.matches(Regex(".*[a-zA-Z].*"))
if (containsAlphabets) {
println("The input string contains alphabetic characters.")
} else {
println("The input string does not contain alphabetic characters.")
}

Upvotes: 2

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You can use .*[a-zA-Z]+.* with String.matches() method.

boolean atleastOneAlpha = s.matches(".*[a-zA-Z]+.*");

Upvotes: 105

Luciano
Luciano

Reputation: 573

The regular expression you want is [a-zA-Z], but you need to use the find() method.

This page will let you test regular expressions against input.

Regular Expression Test Page

and here you have a Java Regular Expressions tutorial.

Java Regular Expressions tutorial

Upvotes: 25

Related Questions