beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – String matches() Method example

By Chaitanya Singh | Filed Under: String handling

Method matches() checks whether the String is matching with the specified regular expression. If the String fits in the specified regular expression then this method returns true else it returns false. Below is the syntax of the method:

public boolean matches(String regex)

It throws PatternSyntaxException – if the specified regular expression is not valid.

Example: matches() method

In this example we have a String and three regular expressions. We are matching the regular expressions(regex) with the input String using the matches() method.

public class MatchesExample{
   public static void main(String args[]){
       String str = new String("Java String Methods");

       System.out.print("Regex: (.*)String(.*) matches string? " );
       System.out.println(str.matches("(.*)String(.*)"));

       System.out.print("Regex: (.*)Strings(.*) matches string? " );
       System.out.println(str.matches("(.*)Strings(.*)"));

       System.out.print("Regex: (.*)Methods matches string? " );
       System.out.println(str.matches("(.*)Methods"));
   }
}

Output:

Regex: (.*)String(.*) matches string? true
Regex: (.*)Strings(.*) matches string? false
Regex: (.*)Methods matches string? true

Enjoyed this post? Try these related posts

  1. Java – String regionMatches() Method example
  2. Java – String toCharArray() Method example
  3. Java String concat() Method example
  4. Java String isEmpty() method with example
  5. Java String trim() and hashCode() Methods with examples
  6. Java String startsWith() Method with example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorials

  • Learn Java
  • OOPs Concepts
  • Java Collections

Java String

  • Java String

Java String Methods

  • String charAt()
  • String compareTo()
  • String compareToIgnoreCase()
  • String contains()
  • String concat()
  • substring
  • String valueOf()
  • String startsWith()
  • String equals()
  • String format()
  • String endsWith()
  • String indexOf()
  • String lastIndexOf()
  • String length()
  • String replace()
  • String split()
  • String trim()
  • String intern()
  • String isEmpty()
  • String matches()
  • String regionMatches()
  • String contentEquals()
  • String toCharArray()
  • String getBytes()
  • String join()
  • String getChars()
  • String copyValueOf()

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap