English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String Match() method checks if the string matches the given regular expression.
The syntax of the string matches() method is:
string.matches(String regex)
Here, string is an object of the String class.
regex - Regular expression
If the regular expression matches the string, thenReturns true
If the regular expression does not match the string, thenReturns false
class Main { public static void main(String[] args) { //Regular expression pattern //A five-letter string that starts with 'a' and ends with 's' String regex = "^a...s$"; System.out.println("abs".matches(regex)); // false System.out.println("alias".matches(regex)); // true System.out.println("an abacus".matches(regex)); // false System.out.println("abyss".matches(regex)); // true } }
Here "^a...s$" is a regular expression that represents a string starting with a and ending with s5a string with only letters s.
//Check if a string contains only numbers class Main { public static void main(String[] args) { //Pattern for searching only numbers String regex = "^[0-9]+$"; System.out.println("123a".matches(regex)); // false System.out.println("98416".matches(regex)); // true System.out.println("98 41".matches(regex)); // false } }
Here "^[0-9]+$" is a regular expression that represents numbers only.