JAVA学习之关于正则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.regextest;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexTest {
 
        //判断字符串是否匹配
	public void matchString(String s){
		Pattern regex = Pattern.compile("(\\.a)");
		Matcher matcher = regex.matcher(s);
		matcher.find();
		System.out.println("the result is " + String.valueOf(matcher.find()));
	}
        //通过正则匹配分割字符串
	public void splitString(String s){
		Pattern regex = Pattern.compile("(\\.a)");
		String[] matcher = regex.split(s);
		for(int i=0;i< matcher.length;i++){
			System.out.println("the "+ String.valueOf(i) +" is " + matcher[i]);
		}
	}
        //找出字符串中所有符合匹配条件的子字符串
	public void getAllMatchString(String s){
		Pattern regex = Pattern.compile("(\\.a)([^.]+)");
		Matcher matcher = regex.matcher(s);
                //记录每一次匹配的开始位置
		int matchIndex = 0;
		while(matcher.find(matchIndex)){
			//matcher.group(n)返回第n个捕获括号中的字符串
			System.out.println(
                              "the start :" + matcher.start() + " , the string is " + matcher.group(2)
                        );
			matchGroup = matcher.end();
		}
	}
	public static void main(String[] args) {
		RegexTest rt = new RegexTest();
		String s = "b.aadfa.aadfaf.a.asadfasdf.b";
//		rt.matchString("b.aadfa.aadfaf.a.asadfasdf.b");
		rt.getAllMatchString(s);
	}
 
}

控制台输出:

1
2
3
the start :0 , the string is adfa
the start :7 , the string is adfaf
the start :14 , the string is sadfasdf
由 晓狼 发表于 2013-07-10 0 评论
标签 :

0 个评论

对不起,评论已关闭.

上一篇文章
«
下一篇文章
»
 友情链接:web集结号     京ICP备11006177号