Home  >  Article  >  Java  >  Detailed explanation of Java regular expression API

Detailed explanation of Java regular expression API

怪我咯
怪我咯Original
2017-04-05 16:39:111411browse

Java中正则表达式相关的类都在java.util.regex之内,一般来说,主要用到的是这两个类:java.util.regex.Patternjava.util.regex.Matcher。Pattern对应正则表达式,一个Pattern与一个String对象关联,生成一个Matcher,它对应Pattern在String中的一次匹配; 调用Matcher对象的find()方法,Matcher对象就会更新为下一次匹配的匹配信息。示例:

Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-]]d{2}");
String string = "2010-12-20 2011-02-14";
Matcher matcher = pattern.matcher(string);
while(matcher.find()) {
    System.out.println(matcher.group(0));
}

Pattern

Pattern是Java语言中的正则表达式对象。要使用正则表达式,首先必须从字符串“编译”出Pattern对象,这需要用到Pattern.compile(String regex)方法。

Pattern pattern = Pattern.compile("a.b+");

如果要指定匹配模式,可以在表达式中使用(?modifier)修饰符指定,也可以使用预定义常量。下面的两个Pattern对象的生成方法不同,结果却是等价的。

Pattern pattern = Pattern.compile("(?i)a.b+");
Pattern pattern = Pattern.compile("a.b+",Pattern.CASE_INSENSITIVE);

如果要同时指定多种模式,可以连写模式修饰符,也可以直接用|运算符将预定义常量连接起来,以下两个Pattern对象也是等价的。

Pattern pattern = Pattern.compile("(?is)a.b+");
Pattern pattern = Pattern.compile("a.b+",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

下面介绍Pattern的主要成员方法:

1. static boolean matches(String regex.CharSequence input)

这个方法可以检验字符串input能否由正则表达式regex匹配,因为是静态方法,所以不需要编译生成各个对象,方便随手使用。要注意的是,它检验的是“整个字符串能否由表达式匹配”,而不是“表达式能否在字符串中找到匹配”。你可以认为regex的首尾自动加上了匹配字符串起始和结束位置的锚点 \A和\z 。

Pattern.matches("\\d{6}","a123456");   //false
Pattern.matches("\\d{6}","123456");     //true

2. String[] split(CharSequence text)

通常,Pattern对象需要配合下面将要介绍的Matcher一起完成正则操作。如果只用正则表达式来切分字符串,只用Pattern的这个方法也可以。

这个方法接收的参数类型是CharSequence它可能有点陌生,其实它是String的父类,其他子类还有CharBuffer,StringBuffer,StringBuilder,因而可以应对常见的各种表示“字符串”的类。下面的代码仅以String为例:

String s = "2010-12-20";
Pattern pattern = Pattern.compile("\\s+");
for(String part : pattern.split(s)){
    System.out.println(part);
}

3. String[] split(CharSequence text,int limit)

这个方法与上面的方法很相似,只是多了一个参数limit,它用来限定返回的String数组的最大长度。也就是说,它规定了字符串至多只能“切”limit-1次。如果不需要对字符串比较大,进行尽可能多的切分,使用这个方法。

String s = " 2010-12-20  ";
Pattern pattern = Pattern.compile("\\s+");
for(String part : Pattern.split(s,2)){
    System.out.println(part);
}

既然limit是一个int类型,那么它自然可以设定为各种值,下表总结了limit在各个取值区间对结果的影响(未指定limit时,最终返回包含n个元素的数组,实际能切分的次数是 n-1 ):

取值                      
结果                                                                                    
limit ffb14e3a63d532ba1d6ec8129b85ee56= n
等于未指定limit时

4. static String quote(String text)

这个方法用来取消字符串text中所有转义字符的特殊含义,实质就是在字符串首尾添加 \Q 和 \E。通常,如果需要把某个字符串作为没有任何特殊意义的正则表达式(比如从外界读入的字符串,用在某个复杂的正则表达式中),就可以使用这个方法:

"aacb".matches("a*.b");            //true
"a*.b".matches("a*.b");             //false
"a*.b".matches("a*.b");             //false
"a*.b".matches(Pattern.quote("a*.b"));        //true

Matcher

Matcher可以理解为“某次具体匹配的结果对象”:把编译好的Pattern对象“应用”到某个String对象上,就获得了作为“本次匹配结果”的Matcher对象。之后,就可以通过它获得关于匹配的信息。

Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher matcher = pattern.matcher("2010-12-20 2011-02-14");
while(matcher.find()){
    System.out.println(matcher.group());
}

对编译好的Pattern对象调用matcher(String text)方法,传入要匹配的字符串text,就得到了Matcher对象,每次调用一次find()方法,如果返回true,就表示“找到一个匹配”,此时可以通过下面的若干方法获得关于本次匹配的信息。

1. String group(int n)

返回当前匹配中第n对捕获括号捕获的文本,如果n为0,则取匹配的全部内容;如果n小于0或者大于最大分组编号数,则报错。

2. String group()

返回当前匹配的全部文本,相当于group(0)。

3. int groupCount()

返回此Matcher对应Pattern对象中包含的捕获分组数目,编号为0的默认分组不计在内。

4. int start(n)

返回当前匹配中第n对捕获括号匹配的文本在原字符串中的起始位置。

5. int start()

返回当前匹配的文本在原字符串中的起始位置,相当于start(0)。

6. int end(n)

返回当前匹配中第n对捕获括号匹配的文本在原字符串中的结束位置。

7. int end()

返回当前匹配的文本在原字符串中的结果位置,相当于end(0)。

8. String replaceAll(String replacement)

如果进行正则表达式替换,一般用到的是Matcher的replaceAll()方法,它会将原有文本中正则表达式能匹配的所有文本替换为replaceement字符串。

String

许多时候只需要临时使用某个正则表达式,而不需要重复使用,这时候每次都生成Pattern对象和Matcher对象再操作显得很烦琐。所以,Java的String类提供了正则表达式操作的静态成员方法,只需要String对象就可以执行正则表达式操作。

1. boolean matches(String regex)

这个方法判断当前的string对象能否由正则表达式regex匹配。请注意,这里的“匹配”指的并不是regex能否在String内找到匹配,而是指regex匹配整个String对象,因此非常适合用来做数据校验。

"123456".matches("\\d{6}");            //true
"a123456".matches("\\d{6}");          //true

2. String replaceFirst(String regex,String replacement)

这个方法用来替换正则表达式regex在字符串中第一次能匹配的文本,可以在replacement字符串中用$num引用regex中对应捕获分组匹配的文本。

"2010-12-20 2011-02-14".replaceFirst("(\\d{4})-(\\d{2})-(\\d{2})","$2/$3/$1");

3. String replaceAll(String regex,String replacement)

这个方法用来进行所有的替换,它的结果等同于Matcher类的replaceAll()方法,replacement字符串中也可以用$num的表示法引用regex中对应捕获分组匹配的文本。

"2010-12-20 2011-02-14".replaceAll("(\\d{4})-(\\d{2})-(\\d{2})","$2/$3/$1");

4. String[] split(String regex)

这个方法等价于Pattern中对应的split()方法,此处不再赘述。

5. String[] split(String regex,int limit)

这个方法等价于Pattern中对应的split()方法,此处不再赘述。

The above is the detailed content of Detailed explanation of Java regular expression API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn