本文共 2639 字,大约阅读时间需要 8 分钟。
正则表达式是一种字符处理工具,可以对字符串进行查找,提取,分割,替换等操作。正则表达式可以理解为一个用于匹配字符串的模板。使用java中的正则表达式时,我们预先定义一个规则,然后看字符串是否符合这个规则。当然我们定义规则时需要借助一些特殊的符号,就是正则表达式中的特殊字符。
java中使用正则有两种方式,1是通过String类直接调用,2是通过Java中的Pattern和Matcher类来使用。 更详细的使用方法见下面的代码和注释。代码如下:
package lkl1;import java.util.regex.Matcher;import java.util.regex.Pattern;public class 正则表达式 { public static void main(String[] args){ //通过字符串直接调用正则表达式 String str = "test java"; //直接通过字符串形式调用正则表达替换时,并不会改变原字符串的值,而是 //另外有别的返回值 String str1 = str.replaceFirst("\\w*", "哈哈"); System.out.println(str1); System.out.println(str.replaceAll("\\w+", "呵呵")); //判断该字符串是否匹配指定的正则表达式(整串匹配) if(str.matches("\\w")){ System.out.println("该字符串中的字母都为单词字符"); } else{ System.out.println("该字符串中含有非单词字符"); } //指定分隔符将该字符串分解为多个子串 String s[] = str.split(" "); for(String ss:s){ System.out.println(ss); } //通过java中的Pattern和Matcher类来使用正则表达式 String st = "java is very easy"; Pattern p = Pattern.compile("\\w+"); //指定正则表达式模式 Matcher m = p.matcher(st); //指定使用正则表达式的字符串 //find();返回字符串中是否有与Pattern匹配的子串 //在一个字符串中find()是依次从前往后查找的各个子串的 //可以传入参数i,表示从第i个位置开始匹配 boolean bl = m.find(); System.out.println(bl); //返回上次与Pattern匹配的子串 //start();返回上次与Pattern匹配子串的起始位置 //end();返回上次与Pattern匹配子串的终止位置 while(m.find()){ System.out.print(m.group()+"\t"); System.out.println("子串的起始位置是: "+m.start()+" 终止位置是: "+m.end()); } //lookingAt()返回目标字符串前面部分是否与Pattern匹配 System.out.println("字符串前面部分是否和Pattern匹配: "+m.lookingAt()); //整个字符串是否与Pattern匹配 System.out.println("整个字符串是否与Pattern匹配: "+m.matches()); //reset(),将现有的matcher用于一个新的字符串 m.reset("lkl"); //综合运用:检查邮箱格式是否正确 String[] mails = { "longkaili@qq.com", "2589681675@163.gov", "1567481@Yalo.org", "acm_lkl@csdn.xoxo" }; Pattern p1 = Pattern.compile("\\w{3,20}@\\w+\\.(com|gov|org)"); //其实也可以直接:"longkaili@qq.com".matcher("\\w{3,20}@\\w+\\.(com|gov|org)") Matcher m1 = null; for(String mail:mails){ if(m1==null){ m1 = p1.matcher(mail); } else{ m1 = m1.reset(mail); } if(!m1.matches()){ System.out.println("邮箱: "+mail+" 命名不合法"); } } }}
转载地址:http://ukrfb.baihongyu.com/