浅谈正则表达式

来源:互联网 发布:电脑应用无法链接网络 编辑:程序博客网 时间:2024/06/05 00:44

正则表达式

什么是正则表达式?

  • 正则表达式也叫规则表达式,是一种特殊的字符串表达式,用于匹配一组字符串。
    • 就好比用模具做产品,而正则表达式就是这个模具,定义一种规则去匹配符合这种规则的字符串。

正则表达式常用字符:

正则表达式的语法:

上图例举了很多常用字符,但还是要拿几种常用的元字符说明一下(自身的理解)

1、三种括号的含义:

  • [ ] 指定范围内任何一个字符

    • 如:[356]、[1-9]、[a-z]表示指定中括号里面的这些数。
    • [^356]、[^abc],^符号表示去除,意思就是除去中括号里面的数。
  • {}指定内容重复次数。

    • 如:{5}、{5,10}
  • ()组合匹配,将若干字符串作为一个整体进行操作。

    • 如:abc{10},就是将c重复10次,而(abc){10}就是将abc重复10次。

2、常用的几种标准元字符(特殊字符)

  • \d = [0-9] 数字字符 (包含0-9所有的数)
  • \D = [^0-9] 非数字字符 (除了0-9之外的数)
  • \w = [0-9a-zA-Z_] (代表任意一个字母、数字和下划线)
  • \W = [^0-9a-zA-Z_] (除了字母、数字和下划线以外的)
  • \s = 空白字符 ( 空格、制表符\t、换行符\n)
  • \S = 非空字符
  • .(点 ) (可以匹配除了换行符\n以外的任意一个字符)
  • . (只匹配.(点))
  • [\s\S] (一般用来匹配任意字符)
  • ? = {0,1} (单个字符)
    • = {1,} (必须有一个字符)
    • = {0,} (任何字符)

正则表达式具体实例:

public class QQ{    public static void main (String[] args){        checkQQ("165184122");    }    private static void checkQQ(String qq){        //定义正则表达式,第一位只能是1-9任意数字,不能为0        //第二位可以是任何        //剩余几位最少4次,但不超过10次(QQ号码不能超过12位)        String regex = "[1-9]\\d{4,10}";          boolean flag = qq.matches(regex);        if(flag){            System.out.println("您的QQ号码为:"+qq);        }else{            System.oy.println("您输入的QQ号码不合法");        }    }}

结果如下:

您的QQ号码为:165184122

还有一种使用正则表达式实现字符串替换的方式:

String对正则表达式的支持:

public class Replace{    public static void main (String[] args){        String str = "7559z5965556b555595g555"//随意定义一个字符串        String str2 = str.replaceAll("\\d","#");//把所有数字 替换成#号        String str3 = str.replaceAll("\\d{4,}","#");//把4个以上连续数字替换成#号    }}

使用Pattern类,利用正则表达式实现对字符串的拆解:

public class TestRegex {//此类目的:利用正则表达式和Pattern类对一组英文语句实现单词的逐个输出。//此方法一般能用在对一遍英文文章进行单词的逐个输出,并去除重复,实现compartor还可以//对单词进行排序功能public static void main(String[] args) {    String str="Among the facilities provided by the System class,re standard input,                                                     standard output, and error output streams";    String regex="\\b[a-zA-Z]+\\b"; //定义正则表达式,取到所有单词    Pattern compile = Pattern.compile(regex);    Matcher matcher = compile.matcher(str);    while(matcher.find()){        System.out.println(matcher.group()+"\t");      }   }} 

输出结果:

AmongthefacilitiesprovidedbytheSystemclassrestandardinputstandardoutputanderroroutputstreams