Java正则表达式1

来源:互联网 发布:linux移动文件夹覆盖 编辑:程序博客网 时间:2024/05/16 08:17

Java正则表达式1

引用

import java.util.regex.Matcher;import java.util.regex.Pattern;

使用:

定义Pattern 对象

Pattern pattern1 = Pattern.compile("\\d+");

定义Matcher 对象(使用上述步骤1定义的Pattern 对象pattern1)

Matcher matcher1 = pattern1.matcher("welcome2223to");

运用:

  • 判断是否匹配到,该方法返回类型为boolean,匹配到返回true, 否则返回false

    matcher1.find();
  • 替换字符串中内容,下面的例子替换字符串“welcome2223to”中的数字,数字用字符‘e’来换

    matcher1.replaceAll("e");

    使用matcher1的group方法,注意前提是正则表示式中出现(),否则匹配不到,抛出异常

    String regEx = "count(\\d+)(df)";       String s = "count000dfdfsdffaaaa1";       Pattern pat = Pattern.compile(regEx);       Matcher mat = pat.matcher(s);       if(mat.find()){        System.out.println(mat.group(2));     }

    参考:

    1. 正则表达式:
      http://deerchao.net/tutorials/regex/regex.htm
    2. 从字符串中提取数字
      http://www.cnblogs.com/android-html5/archive/2012/06/02/2533926.html
    3. Java正则表达式的语法与示例
      http://www.cnblogs.com/lzq198754/p/5780340.html
0 0