Java正则表达式

正则表达式实例

java.util.regex包中定义了如下正则相关的类:

  • Pattern

pattern对象是一个正则表达式的编译标识。该类没有构造方法

Pattern pattern = Pattern.compile("[a-zA-Z]+(\d+)\w");
  • Matcher

matcher是对输入字符串进行解析和匹配操作的引擎。该类没有构造方法

Matcher m = pattern.matcher("DN1800K9");
  • PatternSyntaxException

是一个非强制异常类,表示正则表达式模式中的语法错误。❎

分组匹配

Pattern pattern = Pattern.compile("[a-zA-Z]+(\d+)\w");
Matcher m = pattern.matcher("DN1800K9");
if (m.find())
{
  System.out.println(m.group(0));  // DN1800K9
  System.out.println(m.group(1));  // 1800
}
原文地址:https://www.cnblogs.com/zhuxiang1633/p/13927308.html