regex
Pattern matcher example – Part 2
This is an example of how to use a Pattern Matcher to match an input String with a specified pattern. Matching a String to a pattern with a Matcher implies that you should:
- Compile a String regular expression to a Pattern, using
compile(String regex)
API method of Pattern. - Use
matcher(CharSequence input)
API method of Pattern to create a Matcher that will match the given String input against this pattern. - Use
lookingAt()
API method to match the input sequence, starting at the beginning of the region, against the pattern.
Let’s take a look at the code snippet that follows:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.javacodegeeks.snippets.core; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherPatt { public static void main(String[] args) { Pattern pattern = Pattern.compile( "(\\w+)\s(\\d+)" ); Matcher m = pattern.matcher( "Bananas 123" ); m.lookingAt(); System.out.println( "Name: " + m.group( 1 )); System.out.println( "Number: " + m.group( 2 )); } } |
Output:
Name: Bananas
Number: 123
This was an example of how to use a Pattern Matcher in Java.