Java Pattern类
Pattern类被表示为正则表达式模式的编译版本。Pattern类位于java.util.regex包中。该类具有各种方法,用于匹配、拆分、搜索等各种操作。为了创建一个pattern对象,需要使用compile方法。
语法
public static Pattern compile(String regex)
正则表达式(Regular Expression)是一个字符串,用于编译和匹配模式。可以使用Matcher方法来使用编译后的对象来匹配模式。
步骤
编译和匹配模式的步骤如下:
- 步骤1 - 初始化一个字符串作为正则表达式模式。
-
步骤2 - 使用compile方法来编译模式。
-
步骤3 - 定义要匹配的输入字符串。
-
步骤4 - 创建一个Matcher对象,并将模式应用于输入字符串。
-
步骤5 - 使用Matcher方法执行各种操作。
语法
public class Regex {
public static void main(String[] args) {
String pattern = "String1";
Pattern compiledPattern = Pattern.compile(pattern);
String input = "Strin2";
Matcher matcher = compiledPattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found: " + matcher.group(0));
System.out.println("Captured group: " + matcher.group(1));
} else {
System.out.println("No match found.");
}
}
}
方法1:使用matches()方法
这种方法涉及使用matches()方法。
示例
import java.util.regex.Pattern;
public class MatchThePattern {
public static void main(String[] args) {
String pattern = "Hello (\w+)";
String input = "Hello World"; // Add the input string to be matched
boolean letsMatch = Pattern.matches(pattern, input);
if (letsMatch) {
System.out.println("Pattern matched.");
} else {
System.out.println("Pattern not matched.");
}
}
}
输出
Pattern matched.
解释
通过将两个字符串输入作为参数传递给matches方法,我们可以成功地在上面的代码中匹配两个字符串模式。
方法2:使用find()方法
find()方法返回一个布尔类型,并找到与模式匹配的表达式。以下是一个代码示例 –
示例
在这个示例中,我们将使用find()方法演示方法2。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LetsFindPattern {
public static void main(String[] args) {
String pattern = "\b\d+\b";
String input = "The price is 100 dollars for 3 items.";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(input);
while (matcher.find()) {
System.out.println("Match found: " + matcher.group());
}
}
}
输出
Match found: 100
Match found: 3
方法1和方法2的比较
评判标准 | 方法1 | 方法2 |
---|---|---|
类型 | 字符串 | 字符串 |
方法 | boolean matches(String regex) | boolean find() |
方法逻辑 | 如果匹配成功则返回模式 | 返回匹配的模式 |
结论
正则表达式用于匹配模式。上述方法是匹配模式所需采取的行动的示例。我们还通过两个工作示例展示了这些方法的功能和多样性。通过了解这些方法及其使用案例,您可以通过使用正则表达式高效地找到匹配模式。