在Java中,java.util.regex包定义了正则表达式使用到的相关类,其中最主要的两个类为:Pattern、Matcher。
Pattern 编译正则表达式后创建一个匹配模式。
Matcher 使用Pattern实例提供的正则表达式对目标字符串进行匹配。
替换 1 2 3 4 5 6 7 8 String s = "abc-abc-abc" ; String regex = "-" ; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); String s1 = m.replaceAll(" " ); System.out.println(s1); 结果为: abc abc abc1
分割 1 2 3 4 5 6 7 8 9 10 11 String s = "abc-abc-abc" ; String regex = "-" ; Pattern p = Pattern.compile(regex); String[] list = p.split(s); for (String s1: list){ System.out.println(s1); } 结果为: abc abc abc
Java中String类的split()方法也可以对字符串进行分割。String类的split()源码如下:
1 2 3 4 5 6 7 8 9 10 11 public String[] split(String regex, int limit) { return Pattern.compile(regex).split(this , limit); } public String[] split(String regex) { return split(regex, 0 ); }
用String类的split()来分割字符串:1 2 String s = "abc-abc-abc" ; String[] list = s.split("-" );
那么,两者之间有什么区别呢? 从源码中可以看到,String类的split()实际上是应用Pattern.compile().split(),从本质上来说没有差别。 但是,如果程序中需要多次用到分割,因为使用正则表达式要对正则表达式进行编译,用Pattern的话,效率会提高很多。比如,在一个循环语句中:
1 2 3 4 5 6 7 8 9 10 11 String s = "aaa--bbb--ccc---ddd" ; Pattern p = Pattern.compile("-" ); for (int i = 0 ; i < 10 ; i++) { String[] list = p.split(s); } for (int i = 0 ; i < 10 ; i++) { String[] list = s.split("-" ); }
因此,以同样的正则表达式多次分割字符串时,用Pattern.split()会有更高的效率。
匹配和查找 1 2 3 4 5 6 7 8 9 10 11 12 String s = "abc-123!abc-456!" ; String regex = "[\\d]+(!)" ; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); while (m.find()){ String s1 = m.group(0 ); String s2 = m.group(1 ); System.out.println(s1 + " " + s2); } 结果为: 123 ! !456 ! !
Pattern类方法介绍 1 2 3 4 private Pattern (String p, int f) 私有的构造方法。public static Pattern compile (String regex) 通过静态方法compile创建Pattern对象,查看源代码发现compile直接调用了Pattern构造函数public static Pattern compile (String regex, int flags) 通过静态方法compile创建Pattern对象,查看源代码发现compile直接调用了Pattern构造函数,该方法允许设置多个Match Flag,如Pattern.CASE_INSENSITIVE|Pattern.UNIX_LINES,关于Match Flag后续做详细说明。public String pattern () 返回字符串类型的正则表达式,也就是compile函数的regex参数值。