java 中使用 Pattern匹配正则
import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexExample { public static void main(String[] args) { String regex = "\\d+"; // 正则表达式,表示匹配一个或多个数字 String input = "12345"; // 待匹配的字符串 Pattern pattern = Pattern.compile(regex); // 编译正则表达式 Matcher matcher = pattern.matcher(input); // 创建匹配器对象 while (matcher.find()) { String match = matcher.group(); // 获取匹配到的字符串 System.out.println("Match: " + match); } } }
在上述示例中,我们使用 Pattern.compile
方法将正则表达式 \\d+
编译成一个 Pattern
对象。然后,我们使用 Pattern.matcher
方法创建一个 Matcher
对象,用于在待匹配的字符串中进行搜索和匹配操作。
接下来,我们使用 Matcher.find
方法进行匹配,当找到匹配项时,使用 Matcher.group
方法获取匹配到的字符串,并打印出来。
注意,在正则表达式中使用特殊字符时,需要进行转义。例如,\d
表示匹配数字,但在 Java 中需要使用 \\d
进行转义。
希望这可以帮助到你!