March 24, 2022

Java String matches() Method

In this post we’ll see how to use Java String matches() method which tells whether the String matches the given regular expression or not. This method is useful if you have a bunch of Strings and you want to separate specific type of Strings by passing the specified pattern as a regular expression.

matches() method in String class

  • boolean matches(String regex)- Tells whether or not this string matches the given regular expression.

Method returns true if string matches the given regular expression otherwise false is returned. PatternSyntaxException is thrown if the regular expression's syntax is invalid.

matches() method Java examples

1. In the following example there are two strings and matches method is used to match strings with regular expression. Regex .* means any number of characters so .*knpcode.* means any number of characters before and after knpcode.

public class StringMatch {
  public static void main(String[] args) {
    String str1 = "In technical blog knpcode you will find many interesting Java articles";
    String str2 = "Java programming language is the most used language";
    System.out.println("knpcode found in str1- " + str1.matches(".*knpcode.*"));
    System.out.println("knpcode found in str2- " + str2.matches(".*knpcode.*"));

    System.out.println("Java found in str1- " + str1.matches(".*Java.*"));
    System.out.println("Java found in str2- " + str2.matches(".*Java.*"));
  }
}
Output
knpcode found in str1- true
knpcode found in str2- false
Java found in str1- true
Java found in str2- true

2. In a list of Strings you want to match those strings which have only alphabets. Regular expression [a-zA-Z]+ used in the example matches alphabets a-z both lower case and upper case.

public class StringMatch {
  public static void main(String[] args) {
    List<String> strList = Arrays.asList("abc", "1a2b", "839", "Toy");
    for(String str : strList) {
      // regex to match alphabets
      if(str.matches("[a-zA-Z]+"))
        System.out.println(str);			
    }
  }
}
Output
abc
Toy

That's all for the topic Java String matches() Method. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment