- 论坛徽章:
- 0
|
· Patter类,Matcher常用方法
· 分组
· start(),和end()方法(Matcher)
· start(),和end()方法(Matcher)
· split方法
· 替换操作
· reset
Patter类常用的两个方法:
static,matches(String regex,CharSequence input)
non-static,matcher(String input)
第一个方法用于发现regex是否和input全部匹配,与Matcher提供的matches方法类似。
调用第二个方法产生Matcher对象,Matcher提供了一下的方法:
boolean matches()判断模式是否和整个串匹配
boolean lookingAt()如果input从一开始就是模式的一个匹配,返回true。这个方法并不要求input和regex是完全匹配的。
boolean find()发现charSequence中的多重匹配模式
boolean find(int start)
两个版本find方法的比较:
import java.util.regex.*;
public class CompareFind{
public static void main(String[] args){
String input="Tonight is a beautiful night!";
Matcher m=Pattern.compile(
"\\w+").matcher(input);
System.out.println("Find(): ");
while(m.find()){
System.out.println(m.group());
}
System.out.println("--------------------"
+"\nFind(int start): ");
int i=0;
while(m.find(i)){
System.out.print(m.group()+" ");
i++;
if(i%5==0)
System.out.println();
}
}
}
#输出:
Find():
Tonight
is
a
beautiful
night
--------------------
Find(int start)
Tonight onight night ight ght
ht t is is s
a a beautiful beautiful eautiful
autiful utiful tiful iful ful
ul l night night ight
ght ht t
C:\javawork\useLIB\re>
分组
a(b(c))d有三个组,0组abcd,第一组bc,第二组c
Matcher提供了一些方法返回分组信息
public int groupCount()分组数目,但不包括第0组
public String group()返回第0组的匹配,即整个匹配
public String group(int i)返回第i组的匹配
start(),和end()方法(Matcher)
在匹配操作成功之后调用start和end方法将分别返回匹配的开始和结束位置的下标。在匹配失败之后如果调用这两个方法抛出IllegalStateException
异常。
另外matcher还提供了这两个方法的重载版本start/end(int group)
用于发现在指定分组中的匹配起始和结束位置。
split方法
Pattern.split(String input)
Pattern.split(String input,int limit)限制split的数目
String.split(String )
替换操作
replaceFirst(String regex,String replacement)
replaceAll(String regex,String replacement)
appendReplacement(StringBuffer sbuf,String replacement) appendTail(StringBuffer sbuf,String replacement)
import java.util.regex.*;
public class AppendTest{
public static void main(String[] args){
String input=" hello how are you!";
System.out.println(input);
input=input.replaceFirst(" {2,}","");
System.out.println(input);
input=input.replaceAll(" {2,}"," ");
System.out.println(input);
Pattern p=Pattern.compile("[aeiou]");
Matcher m=p.matcher(input);
StringBuffer sbuf=new StringBuffer();
while(m.find()){
m.appendReplacement(sbuf,m.group().toUpperCase());
}
m.appendTail(sbuf);
System.out.println(sbuf);
}
}
#输出:
hello how are you!
hello how are you!
hello how are you!
hEllO hOw ArE yOU!
reset将现有的Matcher对象用于一个新的字符对象
Matcher m=Pattern.compile("[frb][aiu][gx]").
matcher("fix the rug with bags");
//Some operations
m.reset("fix the rig with rags");
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/63463/showart_570302.html |
|