Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Regular expressions (regex) are a powerful tool for pattern matching. They allow us to find specific patterns within strings, which is very useful for tasks such as data extraction, validation, and transformation.

In this tutorial, we’ll explore how to create a stream of regex matches using a straightforward example.

2. Getting Started

To begin, let’s assume we have a string that includes both letters and numbers:

String input = "There are 3 apples and 2 bananas on the table.";

We aim to extract all the numbers from this string using a regular expression and then create a stream of these matches.

3. Define the Regular Expression

First, we need to define a regex pattern that can match numbers:

String regex = "\\d+";

In this regex, \d+ matches one or more digits. The double backslash \\ is used to escape the backslash character because it’s a special character in Java.

4. Creating a Stream of Matches

Next, we’ll create a Matcher object by applying the defined pattern to our input string:

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

Finally, let’s turn the matched numbers into a stream. We’ll use matcher.results(), a new method introduced in Java 9:

Stream<String> outputStream = matcher.results().map(MatchResult::group);

//Process elements in the stream
outputStream.forEach(System.out::println);

The matcher.results() method returns a stream of MatchResult objects. Each object corresponds to a distinct match found in the input string based on the regex pattern. Then, we can use the group() method of this object to get the matched String.

5. Conclusion

In this article, we’ve learned how to create a stream of regex matches using a simple example of extracting numbers from a string.

The example code from this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.