java--正则表达式操作解析

正则表达式具体写法这里不在叙述,只讲述patternmatcher的用法.

一、捕获组的概念

捕获组可以通过从左到右计算其开括号来编号,编号是从1 开始的。例如,在表达式 ((A)(B(C)))中,存在四个这样的组: 1 ((A)(B(C))) 2 (A) 3 (B(C)) 4 (C) 组零始终代表整个表达式。 以 (?) 开头的组是纯的非捕获 组,它不捕获文本,也不针对组合计进行计数。 与组关联的捕获输入始终是与组最近匹配的子序列。如果由于量化的缘故再次计算了组,则在第二次计算失败时将保留其以前捕获的值(如果有的话)例如,将字符串"aba" 与表达式(a(b)?)+ 相匹配,会将第二组设置为 "b"。在每个匹配的开头,所有捕获的输入都会被丢弃。

二、详解Pattern类和Matcher类

java正则表达式通过java.util.regex包下的Pattern类与Matcher类实现(建议在阅读本文时,打开java API文档,当介绍到哪个方法时,查看java API中的方法说明,效果会更佳).
Pattern类用于创建一个正则表达式,也可以说创建一个匹配模式,它的构造方法是私有的,不可以直接创建,但可以通过Pattern.complie(String regex)简单工厂方法创建一个正则表达式,

Java代码示例:
Pattern p=Pattern.compile(“\w+”);
p.pattern();//返回 \w+

pattern() 返回正则表达式的字符串形式,其实就是返回Pattern.complile(String regex)的regex参数

1.Pattern.split(CharSequence input)

Pattern有一个split(CharSequence input)方法,用于分隔字符串,并返回一个String[],我猜String.split(String regex)就是通过Pattern.split(CharSequence input)来实现的.
Java代码示例:
Pattern p=Pattern.compile(“\d+”);
String[] str=p.split(“我的QQ是:456456我的电话是:0532214我的邮箱是:[email protected]”);

结果:str[0]=”我的QQ是:” str[1]=”我的电话是:” str[2]=”我的邮箱是:[email protected]

2.Pattern.matcher(String regex,CharSequence input)是一个静态方法,用于快速匹配字符串,该方法适合用于只匹配一次,且匹配全部字符串.

Java代码示例:
Pattern.matches(“\d+”,”2223”);//返回true
Pattern.matches(“\d+”,”2223aa”);//返回false,需要匹配到所有字符串才能返回true,这里aa不能匹配到
Pattern.matches(“\d+”,”22bb23”);//返回false,需要匹配到所有字符串才能返回true,这里bb不能匹配到

3.Pattern.matcher(CharSequence input)

说了这么多,终于轮到Matcher类登场了,Pattern.matcher(CharSequence input)返回一个Matcher对象.
Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例.
Pattern类只能做一些简单的匹配操作,要想得到更强更便捷的正则匹配操作,那就需要将Pattern与Matcher一起合作.Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持.
Java代码示例:
Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“22bb23”);
m.pattern();//返回p 也就是返回该Matcher对象是由哪个Pattern对象的创建的

4.Matcher.matches()/ Matcher.lookingAt()/ Matcher.find()

Matcher类提供三个匹配操作方法,三个方法均返回boolean类型,当匹配到时返回true,没匹配到则返回false
matches()对整个字符串进行匹配,只有整个字符串都匹配了才返回true
Java代码示例:
Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“22bb23”);
m.matches();//返回false,因为bb不能被\d+匹配,导致整个字符串匹配未成功.
Matcher m2=p.matcher(“2223”);
m2.matches();//返回true,因为\d+匹配到了整个字符串

我们现在回头看一下Pattern.matcher(String regex,CharSequence input),它与下面这段代码等价
Pattern.compile(regex).matcher(input).matches()

lookingAt()对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true
Java代码示例:
Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“22bb23”);
m.lookingAt();//返回true,因为\d+匹配到了前面的22
Matcher m2=p.matcher(“aa2223”);
m2.lookingAt();//返回false,因为\d+不能匹配前面的aa

find()对字符串进行匹配,匹配到的字符串可以在任何位置.
Java代码示例:
Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“22bb23”);
m.find();//返回true
Matcher m2=p.matcher(“aa2223”);
m2.find();//返回true
Matcher m3=p.matcher(“aa2223bb”);
m3.find();//返回true
Matcher m4=p.matcher(“aabb”);
m4.find();//返回false

5.Mathcer.start()/ Matcher.end()/ Matcher.group()

当使用matches(),lookingAt(),find()执行匹配操作后,就可以利用以上三个方法得到更详细的信息.
start()返回匹配到的子字符串在字符串中的索引位置.
end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
group()返回匹配到的子字符串
Java代码示例:
Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“aaa2223bb”);
m.find();//匹配2223
m.start();//返回3
m.end();//返回7,返回的是2223后的索引号
m.group();//返回2223

Mathcer m2=m.matcher(“2223bb”);
m.lookingAt(); //匹配2223
m.start(); //返回0,由于lookingAt()只能匹配前面的字符串,所以当使用lookingAt()匹配时,start()方法总是返回0
m.end(); //返回4
m.group(); //返回2223

Matcher m3=m.matcher(“2223bb”);
m.matches(); //匹配整个字符串
m.start(); //返回0,原因相信大家也清楚了
m.end(); //返回6,原因相信大家也清楚了,因为matches()需要匹配所有字符串
m.group(); //返回2223bb

说了这么多,相信大家都明白了以上几个方法的使用,该说说正则表达式的分组在java中是怎么使用的.
start(),end(),group()均有一个重载方法它们是start(int i),end(int i),group(int i)专用于分组操作,Mathcer类还有一个groupCount()用于返回有多少组.
Java代码示例:
Pattern p=Pattern.compile(“([a-z]+)(\d+)”);
Matcher m=p.matcher(“aaa2223bb”);
m.find(); //匹配aaa2223
m.groupCount(); //返回2,因为有2组
m.start(1); //返回0 返回第一组匹配到的子字符串在字符串中的索引号
m.start(2); //返回3
m.end(1); //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置.
m.end(2); //返回7
m.group(1); //返回aaa,返回第一组匹配到的子字符串
m.group(2); //返回2223,返回第二组匹配到的子字符串

现在我们使用一下稍微高级点的正则匹配操作,例如有一段文本,里面有很多数字,而且这些数字是分开的,我们现在要将文本中所有数字都取出来,利用java的正则操作是那么的简单.
Java代码示例:
Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“我的QQ是:456456 我的电话是:0532214 我的邮箱是:[email protected]”);
while(m.find()) {
System.out.println(m.group());
}

输出:
456456
0532214
123

如将以上while()循环替换成
while(m.find()) {
System.out.println(m.group());
System.out.print(“start:”+m.start());
System.out.println(” end:”+m.end());
}
则输出:
456456
start:6 end:12
0532214
start:19 end:26
123
start:36 end:39

现在大家应该知道,每次执行匹配操作后start(),end(),group()三个方法的值都会改变,改变成匹配到的子字符串的信息,以及它们的重载方法,也会改变成相应的信息.
注意:只有当匹配操作成功,才可以使用start(),end(),group()三个方法,否则会抛出java.lang.IllegalStateException,也就是当matches(),lookingAt(),find()其中任意一个方法返回true时,才可以使用.

正则替换

正则表达式在替换文本方面特别在行。下面就是一些方法:

replaceFirst(String replacement)将字符串里,第一个与模式相匹配的子串替换成replacement。

replaceAll(String replacement),将输入字符串里所有与模式相匹配的子串全部替换成replacement。

appendReplacement(StringBuffer sbuf, String replacement)对sbuf进行逐次替换,而不是像replaceFirst( )或replaceAll( )那样,只替换第一个或全部子串。这是个非常重要的方法,因为它可以调用方法来生成replacement(replaceFirst( )和replaceAll( )只允许用固定的字符串来充当replacement)。有了这个方法,你就可以编程区分group,从而实现更强大的替换功能。

调用完appendReplacement( )之后,为了把剩余的字符串拷贝回去,必须调用appendTail(StringBuffer sbuf, String replacement)。

下面我们来演示一下怎样使用这些替换方法。说明一下,这段程序所处理的字符串是它自己开头部分的注释,是用正则表达式提取出来并加以处理之后再传给替换方法的。

//: c12:TheReplacements.java
import java.util.regex.*;
import java.io.*;
import com.bruceeckel.util.*;
import com.bruceeckel.simpletest.*;
/*! Here's a block of text to use as input to the regular expression matcher. Note that we'll first extract the block of text by looking for the special delimiters, then process the extracted block. !*/
publicclass TheReplacements {
privatestatic Test monitor = new Test();
publicstaticvoid main(String[] args) throws Exception {
    String s = TextFile.read("TheReplacements.java");
// Match the specially-commented block of text above:
    Matcher mInput =
      Pattern.compile("///*!(.*)!//*/", Pattern.DOTALL)
        .matcher(s);
if(mInput.find())
      s = mInput.group(1); // Captured by parentheses
// Replace two or more spaces with a single space:
    s = s.replaceAll(" {2,}", " ");
// Replace one or more spaces at the beginning of each
// line with no spaces. Must enable MULTILINE mode:
    s = s.replaceAll("(?m)^ +", "");
    System.out.println(s);
    s = s.replaceFirst("[aeiou]", "(VOWEL1)");
    StringBuffer sbuf = new StringBuffer();
    Pattern p = Pattern.compile("[aeiou]");
    Matcher m = p.matcher(s);
// Process the find information as you
// perform the replacements:
while(m.find())
      m.appendReplacement(sbuf, m.group().toUpperCase());
// Put in the remainder of the text:
    m.appendTail(sbuf);
    System.out.println(sbuf);
    monitor.expect(new String[]{
"Here's a block of text to use as input to",
"the regular expression matcher. Note that we'll",
"first extract the block of text by looking for",
"the special delimiters, then process the",
"extracted block. ",
"H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tO",
"thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'll",
"fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr",
"thE spEcIAl dElImItErs, thEn prOcEss thE",
"ExtrActEd blOck. "
    });
  }
} ///:~

用TextFile.read( )方法来打开和读取文件。mInput的功能是匹配’/!’ 和 ‘!/’ 之间的文本(注意一下分组用的括号)。接下来,我们将所有两个以上的连续空格全都替换成一个,并且将各行开头的空格全都去掉(为了让这个正则表达式能对所有的行,而不仅仅是第一行起作用,必须启用多行模式)。这两个操作都用了String的replaceAll( )(这里用它更方便)。注意,由于每个替换只做一次,因此除了预编译Pattern之外,程序没有额外的开销。

replaceFirst( )只替换第一个子串。此外,replaceFirst( )和replaceAll( )只能用常量(literal)来替换,所以如果每次替换的时候还要进行一些操作的话,它们是无能为力的。碰到这种情况,得用appendReplacement( ),它能在进行替换的时候想写多少代码就写多少。在上面那段程序里,创建sbuf的过程就是选group做处理,也就是用正则表达式把元音字母找出来,然后换成大写的过程。通常你得在完成全部的替换之后才调用appendTail( ),但是如果要模仿replaceFirst( )(或”replace n”)的效果,你也可以只替换一次就调用appendTail( )。它会把剩下的东西全都放进sbuf。

你还可以在appendReplacement( )的replacement参数里用”$g”引用已捕获的group,其中’g’ 表示group的号码。不过这是为一些比较简单的操作准备的,因而其效果无法与上述程序相比。


都是摘自网络上的一些笔记

你可能感兴趣的:(正则表达式)