您的位置:首页 > 编程语言 > Java开发

java.util.regex 正则表达式

2011-11-11 11:38 344 查看
转自http://blog.csdn.net/xiazdong/article/details/6793715

正则表达式主要在java.util.regex包中,有Pattern和Matcher类。

Pattern类主要是正则匹配规则,Matcher是用某个正则表达式去匹配字符串。





Pattern和Matcher提供的常用方法:

view
plain

Pattern p = Pattern.compile(String regex);

Matcher m = p.matcher(String str);

boolean b = m.matches();

view
plain

String[] str = Pattern.compile(String regex).split(String str);

String str = Pattern.compile(String regex).matcher(String str).replaceAll(String replace);

代码示例:

(1)匹配日期格式yyyy-MM-dd格式:

view
plain

Pattern.compile("\\d{4}-\\d{2}-\\d{2}").matcher(str).matches();

(2)匹配5个以上的数字:

view
plain

"\\d{5,}"

(3)匹配一个以上数字:

view
plain

"\\d+"

(4)用“_”替换数字

view
plain

String str = Pattern.compile("\\d").matcher("abc123abc").replaceAll("_");

(5)以数字为分割:

view
plain

String[]str = Pattern.compile("\\d+").split("abc123abc");

view
plain

import java.util.regex.*;

public class RegularDemo01{

public static void main(String args[]){

String str = "1234567890";

if(Pattern.compile("\\d*").matcher(str).matches()){

System.out.println("是由数字组成!");

}

else{

System.out.println("不是由数字组成!");

}

String str2 = "2010-10-10";

if(Pattern.compile("\\d{4}-\\d{2}-\\d{2}").matcher(str2).matches()){

System.out.println("是日期格式");

}

else{

System.out.println("不是日期格式");

}

String str3 = "ab1ca2bc";

String[] lists = Pattern.compile("\\d").split(str3);

for(String e : lists){

System.out.println(e);

}

String str4 = "ab1ca2bc";

String lists2 = Pattern.compile("\\d").matcher(str4).replaceAll("-");

System.out.println(lists2);



String str5 = "abc123abc123";

System.out.println(str5.matches("\\w+"));



String info = "XIAZDONG:100|xzdong:90|xiazhengdong:100";

String s[] = info.split("[:|]");

for(int i=0;i<s.length;i+=2){

System.out.println(s[i]+"-->"+s[i+1]);

}

String ss = Pattern.compile("\\d").matcher("abc123abc").replaceAll("_");

System.out.println(ss);

}

}

字符串中也提供了正则表达式的方法:

(1)matches(String regex);

(2)replaceAll(String regex,String replace);

(3)split(String regex);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: