Home >Java >javaTutorial >Pattern matches() method in Java and its examples

Pattern matches() method in Java and its examples

WBOY
WBOYforward
2023-08-30 11:13:02860browse

Java 中的模式 matches() 方法及其示例

java's java.util.regex package provides various classes to find specific patterns in sequences of characters. The package's pattern classes are compiled representations of regular expressions. The

matches()

method of the Pattern class accepts a string value -

  • representing a regular expression.

  • An object of the CharSequence class representing the input string.

    p>

When called, this method matches the input string against a regular expression. This method returns a boolean value that is true if there is a match, false otherwise.

Example

import java.util.Scanner;
import java.util.regex.Pattern;
public class MatchesExample {
   public static void main(String[] args) {
      //Getting the date
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter date string in [dd/mm/yyy] format: ");
      String date = sc.next();
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      //Creating a pattern object
      boolean result = Pattern.matches(regex, date);
      if(result) {
         System.out.println("Date is valid");
      } else {
         System.out.println("Date is not valid");
      }
   }
}

Output 1

Enter date string in [dd/mm/yyy] format:
01/12/2019
Date is valid

Output 2

Enter date string in [dd/mm/yyy] format:
2019-21-12
Date is not valid

The above is the detailed content of Pattern matches() method in Java and its examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete