正则表达式

来源:互联网 发布:药理学 知乎 编辑:程序博客网 时间:2024/06/16 16:02
import java.util.regex.Matcher;import java.util.regex.Pattern;/** *  *//** * @author __LcukyStar * 正则表达式 */public class Test {/** * @param args */public static void main(String[] args) {// 一个点代表一个字符。print("abc".matches("...")); // true// \d代表数字,*代表0个或多个。print("123".matches("\\d*")); // true// [a,z]代表在字符a~z之中的一个,+表示一个或多个print("abc".matches("[a-z]+")); // true// ?表示0个或1个print("a".matches("[a-z]?")); // true// [a-z[A-Z]]表示所有英文字母,并集的意思了。print("abcD".matches("[a-z[A-Z]]*")); // true////////////////////////////////////////////////////////[a-z][a-b]API说是并集,怎么感觉不对。应该是交集吧print("abc".matches("[a-z][a-b]*"));// falseprint("abc".matches("[a-z][a-d]*")); // true/////////////////////////////////////////////////////// {m,n}表示前面的字符出现m到n次,即>=m && <=nprint("abc".matches("[a-c]{1,3}")); // true// {m}表示前面的字符出现m次print("abc".matches("[a-d]{3}")); // true// {m,}表示前面的字符出现的次数>=mprint("abc".matches("[a-d]{2,}")); // true// 或,a,b或c,d之一print("abcd".matches("[[a-b]|[c-d]]*")); // true// a-d并且a-c出现一次或多次print("abc".matches("[[a-d]&&[a-c]]+")); // true// a-c的字符出现3次,D-F的字符出现3次,g,h,i字符之一出现3次,后跟一个数字print("abcDEFghi0".matches("[a-c]{3}[D-F]{3}[g,h,i]{3}\\d")); // true// \D:非数字,等同于[^0-9]print("abd~!@#$%^^&".matches("\\D*")); // true// ^在[]表示,除了xx,如下面就是除了d之外print("abc".matches("[^d]+")); // true// 除了c-f之外的字符0个或多个。print("abc".matches("[^c-f]*")); // false// 以a开头,后跟0到多个字符并且以c结尾print("abc".matches("^a[a-z]*c{1}quot;)); // true// \s:空白字符[ \t\n\x0B\f\r]print(" \n\r\t\f".matches("\\s+")); // true// 非空白在字符print("abcEDF123!@#~".matches("\\S*")); // true// \w:单词字符:[a-zA-Z_0-9]print("abc_DEF_0_23445".matches("\\w+")); // true// \W:非单词字符:[^\w]print("~!@#@%@#%@#%".matches("\\W+")); // trueprint("hello world".matches("z{0}"));print("------------------华丽分割线-----------------");print("hello 168".matches(".*\\b.*")); // trueprint("hello 168".matches(".*.*")); // trueprint("hello168".matches(".*\\b.*")); // trueprint("------------------华丽分割线-----------------");print("aaa@qq.com".matches("\\w[.-]+\\.\\w[.-]+"));print("------------------华丽分割线-----------------");Pattern p = Pattern.compile("\\d{2,3}");String str = "12-234-5678";Matcher m = p.matcher(str);// matches()方法匹配整个字符串print(m.matches()); // 是否匹配给定的正则表达式//m.reset(); // matches()方法在12-时就返回,因为它匹配的是整个字符串,但是下次会从这个位置开始,因此用reset()方法将其重置。print("------------------华丽分割线-----------------");print(m.find()); // true,找到234print(m.find()); // true,找到567print(m.find()); // falseprint(m.find()); // falseprint(m.find()); // falseprint("------------------华丽分割线-----------------");// 从开始位置找,找到了就返回trueprint(m.lookingAt()); // trueprint(m.lookingAt()); // trueprint(m.lookingAt()); // trueprint(m.lookingAt()); // true}public static void print(Object obj) {System.out.println(obj);}}