教程集 www.jiaochengji.com
教程集 >  脚本编程  >  java  >  正文 java 正则表达式函数Pattern.matcher()的使用方法

java 正则表达式函数Pattern.matcher()的使用方法

发布时间:2017-12-12   编辑:jiaochengji.com
教程集为您提供java 正则表达式函数Pattern.matcher()的使用方法等资源,欢迎您收藏本站,我们将为您提供最新的java 正则表达式函数Pattern.matcher()的使用方法资源

public   Pattern.matcher(CharSequence   input)   得到一个要比较字符序列是input的比较器(matcher)  
public   static   boolean   Pattern.matches(String   regex,CharSequence   input)
在字符序列input查找正则表达式regex对应的pattern,
等同与Pattern.compile(regex).matcher(input).matches();
如果regex要使用多次,请使用下面的形式,可以省去编译regex的时间
Pattern   partn   =   Pattern.compile(regex);
partn.matcher(input).matches();


match()的参数一般为正则表达式,现在两个正则表达式,可以试用
正则表达式一:可以适用任何形式的字符串,
其中LikeType是要匹配的字符串,patten是生成的正则表达式,sourceStr是已有字符串,判断sourceStr是否满足LikeType的正则表达式

<blockquote>public static void main(String[] args) {
  // TODO Auto-generated method stub
  String likeType = "23";
  String pattern = "[a-zA-Z0-9]*[" likeType "]{1}[a-zA-Z0-9]*";
  String sourceStr = "adfjaslfj23ldfalsf";
     System.out.println(sourceStr.matches(likeType));
 }</blockquote>

正则表达式二:固定位置的字符串匹配,理解同上,只是正则表达式的不同

<blockquote>public static void main(String[] args) {
  // TODO Auto-generated method stub
  String likeType = "%%#%%%*";
  String sourceStr = "423236664";
  likeType = likeType.replaceAll("%", "\d").replaceAll("*", "\d*");
  System.out.println(likeType);
     System.out.println(sourceStr.matches(likeType));
 }</blockquote>

电话号正则表达式

<blockquote>

public class Main {
  public static void main(String args[]) {
    String phone = "(111)-111-1111";
    String phoneNumberPattern = "(d-)?(d{3}-)?d{3}-d{4}";
    System.out.println(phone.matches(phoneNumberPattern));
  }
}

</blockquote>

match的方法比较简单,但绝对实用,所以要掌握用法,正则表达式的写法尤其重要

 

 

<blockquote>

邮箱号

public class Main {
  public static void main(String[] a) {
    String zip = "1234-123";
    String zipCodePattern = "d{5}(-d{4})?";
    boolean retval = zip.matches(zipCodePattern);

  }
}

日期合法性正则

public class Main {
  public static void main(String[] argv) throws Exception {

    boolean retval = false;
    String date = "12/12/1212";
    String datePattern = "d{1,2}-d{1,2}-d{4}";
    retval = date.matches(datePattern);

  }
}

</blockquote>

您可能感兴趣的文章:
Java中常用正则表达式
java 正则表达式函数Pattern.matcher()的使用方法
正则表达式 模式匹配 Javascript
javascript正则表达式简明教程
学习javascipt的正则表达式
js 正则表达式的replace函数用法
php正则ereg ereg_replace eregi eregi_replace split
通过实例学习php正则表达式之正则处理函数(preg_match,preg_match_all,preg_replace,preg_split)
小白入门必看的Python正则表达式
php正则表达式完全教程(一)

[关闭]
~ ~