In this Java Regex Tutorial we want to learn about Java Regex Pattern Matching, so as we know that Java is popular programming language and it is is used for building web applications, desktop applications and mobile applications. in this article we want to talk about the basics of Java regex pattern matching and some examples that how we can use that.
What is regular expression ?
Regular expression or regex is a sequence of characters that defines a search pattern. Regexes are used to match patterns in text and also it can be used for different type of tasks, for example we can validate an input, we can search for specific text patterns and also we can extract data from text.
In Java, regexes are implemented using java.util.regex package. this package provides two classes, Pattern and Matcher. Pattern class represents a compiled regex pattern, and also Matcher class is used to match the pattern against a given input.
Now let’s create our example in regex, for creating a regex pattern in Java, first of all you need to define the pattern using a sequence of characters that represent the pattern you want to match. for example if you want to match a sequence of digits, you can use the pattern \d+. this pattern matches one or more digits.
After that you have defined your pattern, you can compile it using Pattern.compile() method. this method returns a Pattern object that you can use to match the pattern against a given input.
This is an example of how to create a regex pattern that matches a sequence of digits.
1 2 |
String patternString = "\\d+"; // Define the pattern Pattern pattern = Pattern.compile(patternString); // Compile the pattern |
After that you have compiled your regex pattern, you can use Matcher class to match the pattern against a given input. Matcher class provides several methods for matching the pattern against the input such as matches(), find() and replaceAll().
This is an example of how to use the Matcher class to match a regex pattern, in this example we have defined a pattern that matches any three letter word using the pattern \b\w{3}\b. after that we have used the Pattern class to compile the pattern and the Matcher class to match the pattern against a given input string. also while loop iterates over each match found in the input string and prints the matched text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "Welcome to codeloop.org"; String patternString = "\\b\\w{3}\\b"; // Match any three-letter word Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println(matcher.group()); } } } |
This will be the result
Subscribe and Get Free Video Courses & Articles in your Email