读书人

JAVA中正则的几种运用

发布时间: 2012-12-27 10:17:10 作者: rapoo

JAVA中正则的几种应用

纯属复习,直接上test类:

?

package com.test;import java.util.regex.Matcher;import java.util.regex.Pattern;import junit.framework.TestCase;public class TestPattern extends TestCase {@Overrideprotected void setUp() throws Exception {super.setUp();}public void test_1() {Pattern pattern = Pattern.compile("(\\d{11})(\\d*)");Matcher matcher = pattern.matcher("a159612580111as138090738612ddd");// 打印全部符合的内容一共循环2次,该字符串有2个内容符合正则while (matcher.find()) {for (int i = 1; i <= matcher.groupCount(); i++)System.out.println(matcher.group(i));}}public void test_2() {Pattern pattern = Pattern.compile("(,)|(\\.)|(&)");Matcher matcher = pattern.matcher("我不知道,但是我详细you&me一定能成功.MUST!");StringBuffer sb = new StringBuffer();while (matcher.find()) {// 符合正则的符号全部替换成#matcher.appendReplacement(sb, "#");}// 补齐字符串其他部分matcher.appendTail(sb);System.out.println(sb.toString());}public void test_3() {String str = "http://192.168.3.11:50070/data/1_upload/a.rar";String str1 = "(http://.*/data/)(.*/)(.*)";Pattern p = Pattern.compile(str1);Matcher m = p.matcher(str);while (m.find()) {System.out.println(m.group(1));System.out.println(m.group(2));System.out.println(m.group(3));}}}

读书人网 >编程

热点推荐