首页 > java > java正则表达式

java正则表达式

2011年8月3日 2,440 views

从jdk1.4开始,java推出了java.util.regex包,支持正则表达式。
此包下只有如下两个实现类:
Pattern
Matcher

- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - –
典型用法如下:

Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();

如果仅使用一次正则表达式,也可如下:

boolean b = Pattern.matches("a*b", "aaaaab");

- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - –
说说Pattern

其实,Pattern的用法是比较简单的,除了上面的用法,还可以加标志位,如下:

Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE);

这句代码表示,不区分大小写的匹配以符合 Unicode Standard 的方式完成;
如果没有Pattern.UNICODE_CASE,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。
官方API注释,指定此标志(Pattern.UNICODE_CASE)可能对性能产生影响。

- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - –
说说Matcher的find()、lookingAt()、matches()、group()、replaceAll()

find()、lookingAt()、matches()均返回boolean值,表示匹配是否成功。
可以理解为,它们对匹配成功的要求是依次增强的。如:

String str1 = "abc123";
String str2 = "ab";
String reg1 = "bc";
String reg2 = "ab";

Pattern pattern = Pattern.compile(reg1);
Matcher matcher = pattern.matcher(str1);
matcher.find()//true
matcher.lookingAt()//false
matcher.matches()//false

pattern = Pattern.compile(reg2);
matcher = pattern.matcher(str1);
matcher.find()//true
matcher.lookingAt()//true
matcher.matches()//false

pattern = Pattern.compile(reg2);
matcher = pattern.matcher(str2);
matcher.find()//true
matcher.lookingAt()//true
matcher.matches()//true

即find为全文内部匹配即可,lookingAt需开头匹配,matches为整个字符串都要和表达式匹配。
group()和以上三个方法,是先后、外内的关系。需要先找到匹配的内容,然后在匹配的内容里再进行group()。

public class Test {
	
	public static void main(String[] args) {
		String str = "abcd1234Abcd";
		String reg = "a(b(cd))";
		Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(str);
		while(matcher.find()){
			System.out.println(matcher.group(0));
			System.out.println(matcher.group(1));
			System.out.println(matcher.group(2));
		}
	}
		
}

输出:
abcd
bcd
cd
Abcd
bcd
cd

有时需要将匹配的内容替换,replaceAll()的用法举个例子吧:

public class Test {
	
	public static void main(String[] args) {
		String str = "abcd1234Abcd";
		String reg = "a(b(cd))";
		Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(str);
		System.out.println(matcher.replaceAll("$2\\$-"));
	}
		
}

输出:
cd$-1234cd$-

注意这里的$2和\\$的用法。

-
-
-
-
-
-

-
-
-
-
-
-

分类: java 标签: ,
  1. 本文目前尚无任何评论.