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
We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.
To check if String contains only alphabets in Java, call matches() method on the string object and pass the regular expression "[a-zA-Z]+" that matches only if the characters in the given string is alphabets (uppercase or lowercase).
To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise. Copied!
To check if a string contains at least one number using regex, you can use the \d regular expression character class in JavaScript. The \d character class is the simplest way to match numbers.
You can use .*[a-zA-Z]+.*
with String.matches()
method.
boolean atleastOneAlpha = s.matches(".*[a-zA-Z]+.*");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With