String class in Java is one of the most important and one of the most used class too. To make the usage of String class easier for developers it has many utility methods that can be used out of the shelf. One such method is the matches() method in Java String class that is used to match a string against the given regular expression.
Java String matches() method
- boolean matches(String regex)- Tells whether or not this string matches the given regular expression.
Method returns true if this string matches the given regular expression otherwise false. If the passed regular expression's syntax is invalid then the method throws PatternSyntaxException.
matches() method examples
1. If you have a list of cities and you want to print only those cities that start with “L” then you can pass a regex in matches() method to match that pattern.
import java.util.Arrays; import java.util.List; public class StringMatching { public static void main(String[] args) { List<String> strList = Arrays.asList("Chicago", "London", "Lisbon", "Mumbai"); for(String str : strList) { if(str.matches("L.*")) System.out.println(str); } } }
Ouput
London Lisbon
2. Let's say there is a String array with some strings and you want to match and print only those strings which doesn't contain any digit or special character. Then using matches method and providing a regular expression [a-z]+ which will match one or more chars it can be done as follows.
public class StringComparison { public static void main(String[] args) { String[] words = {"a123","*67t","test","54&ty"}; for(String str : words){ if(str.matches("[a-z]+")){ System.out.println("matched string - " + str); } } } }
Ouput
matched string - test
3. In the same scenario as example 2 if you want to get only those string which are alphanumeric (i.e. no special characters) then using String matches() method it can be done as
public class StringMatching { public static void main(String[] args) { String[] words = {"a123","*67t","test","54&ty"}; for(String str : words){ if(str.matches("\\w+")){ System.out.println("matched string - " + str); } } } }
Ouput
matched string - a123 matched string - test
That's all for this topic matches() method in Java String. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Basics Tutorial Page
Related topics
You may also like-
No comments:
Post a Comment