Java String matches method is a case-sensitive method used to check whether the string is getting matched with the given regular expression or not.
Java matches() method Example
- "hello world".matches("hello(.*)")
Output: true
- "hello world".matches("(.*)world)")
Output: true
- "hello world".matches("to")
Output: false
Java matches() method Syntax
String.matches(regex)
matches() method Parameters
regex-a regular expression.
matches() method Return
This method returns a boolean value-
Returns true-when the regular expression(regex) matches with the given string.
Returns false-when the regular expression(regex) doesn't matches with the given string.
Java matches() method Program
package codesdope;
import java.util.*;
public class codesdope
{
public static void main(String[] args)
{
String s1="Welcome to Codesdope";
System.out.println(s1.matches("Welcome(.*)")); //case-1
System.out.println(s1.matches("to")); //case-2
System.out.println(s1.matches("(.*)Codesdope")); //case-3
}
}
true
false
true
- In the first case, we are applying the matches() method on the string s1 i.e "Welcome to Codesdope" to check whether the input regex "Welcome(.*)" getting matched or not and it returned true.
- In the second case, we are applying the matches() method on the string s1 i.e"Welcome to Codesdope" to check whether the input regex "to" getting matched or not and it returned false.
- In the last case, we are applying the matches() method on the string s1 i.e "Welcome to Codesdope" to check whether the input regex "(.*)Codesdope" getting matched or not and it returned true.