1. Overview
1.概述
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.
正则表达式 (regex) 是一种强大的模式匹配工具。它们允许我们查找字符串中的特定模式,这对数据提取、验证和转换等任务非常有用。
In this tutorial, we’ll explore how to create a stream of regex matches using a straightforward example.
在本教程中,我们将通过一个简单的示例来探讨如何创建 regex 匹配流。
2. Getting Started
2.开始
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
3.定义正则表达式
First, we need to define a regex pattern that can match numbers:
首先,我们需要定义一个可以匹配数字的 regex 模式:
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.
在此 regex 中,/d+ 匹配一个或多个数字。双反斜杠 \ 用于转义反斜杠字符,因为它在 Java 中是一个特殊字符。
4. Creating a Stream of Matches
4.创建匹配流</em
Next, we’ll create a Matcher object by applying the defined pattern to our input string:
接下来,我们将创建一个 Matcher 对象,对输入字符串应用定义的模式:
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:
最后,让我们将匹配的数字转化为数据流。我们将使用 matcher.results() 这个在 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.
matcher.results() 方法会返回 MatchResult 对象流。每个对象都对应于根据 regex 模式在输入字符串中找到的一个不同匹配。然后,我们可以使用该对象的 group() 方法来获取匹配的 String. 对象。
5. Conclusion
5.结论
In this article, we’ve learned how to create a stream of regex matches using a simple example of extracting numbers from a string.
在本文中,我们以从字符串中提取数字为例,学习了如何创建 regex 匹配流。
The example code from this article can be found over on GitHub.