Home > Java > javaTutorial > body text

Pattern matches() method in Java and its examples

WBOY
Release: 2023-08-30 11:13:02
forward
801 people have browsed it

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");
      }
   }
}
Copy after login

Output 1

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

Output 2

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!