{{announcement.body}}
{{announcement.title}}

Matching Patterns With Java

DZone 's Guide to

Matching Patterns With Java

Learn more about matching patterns in Java.

· Java Zone ·
Free Resource

Learn more about matching patterns in Java.

If you're using Java, there's a high chance you've seen its pattern matching before. The String#matches(String) method internally uses the Pattern type, which comprises more complex functionality:

A Pattern is created by compiling a regular expression. The pattern matches any input string and can optionally find capturing groups, which isolate certain parts of your string data.

You may also like: Java Regex: Simple Patterns

The API is used as follows:

Java




x


 
1
Pattern pattern = Pattern.compile("([\\^\\S]+) is powerful");
2
Matcher matcher = pattern.matcher("Java is powerful");
3
 
            
4
System.out.println(matcher.find()); // true
5
System.out.println(matcher.group()); // Java is powerful
6
System.out.println(matcher.group(1)); // Java



The find() method finds the next occurrence of the pattern, which matches the whole input string in this example. The group() method returns either the whole capturing group, that is, matching the whole pattern, or, when qualified with an index, returns the individual capturing groups. The capturing groups indexes start at 1, not at 0.

There's also a matches() method which works slightly differently:

Java




xxxxxxxxxx
1


1
Pattern pattern = Pattern.compile("([\\^\\S]+) is powerful");
2
Matcher matcher = pattern.matcher("Our Java is powerful");
3
 
            
4
System.out.println(matcher.matches()); // false
5
System.out.println(matcher.find()); // true



matches() attempts to match the whole input string to the pattern, from start to end, while find() only tries to find the patterns somewhere in the input string.

Also, as a reminder: Please use the shortcut methods String#matches(String) or Pattern#matches(String, CharSequence) only for single matching invocations that are not repeated over and over again. Patterns are rather heavy to compile and we should leverage the immutability of the Pattern type and reuse it for multiple matches.

Found the post useful? Give it a like and/or save!

Further Reading

Java Regex: Simple Patterns

The ABC's of Regex

Scala: Pattern Matching

Topics:
java ,tutorial ,matching patterns ,patterns

Published at DZone with permission of Sebastian Daschner , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}