正则表达式

前言: 本文共3节,1节:大体介绍,2节:知识点详细介绍,3节:相关案例

1.0 第一部分 (大体介绍)

基本语法:

在java 中使用 : (有的在线工具,可以直接转成各种语言的代码,很方便)

在线工具推荐网址: 点击跳转

在linux 中使用:

2.0 第二部分 (知识点介绍)

核心语法:入门案例 理解(位置 类型 个数)的含义

基本语法

字符表补充:

java 中使用正则, 需要是用”\“ 脱去特殊字符

java中有两种方式使用 正则 ,一种是patton & matcher ; 一种是String , 但本质是一样的。String 底层是patton & Matche

3.0 第三部分 (相关案例)

java匹配字符实例(使用正则对象)


@Test
public void e() {
    //  有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数

    int num = 0;
    int num1 = 0;
    int num2 = 0;
    Pattern compile = Pattern.compile( "[\u4E00-\u9FA5]" );
    Pattern compile1 = Pattern.compile( "[\\d]" );
    Pattern compile2 = Pattern.compile( "[a-zA-Z]" );
    String a = "我的世是界是abc圆的1234567";
    for (int i = 0; i < a.length(); i++) {
        Matcher matcher = compile.matcher( a.charAt( i ) + "" );
        Matcher matcher1 = compile1.matcher( a.charAt( i ) + "" );
        Matcher matcher2 = compile2.matcher( a.charAt( i ) + "" );
        if (matcher.find()) {
            num++;
        }
        if (matcher1.find()) {
            num1++;
        }
        if (matcher2.find()) {
            final String a1 = matcher2.group( 0 );
            num2++;
        }


    }
    System.out.println( "汉字的个数是:" + num );
    System.out.println( "字母的个数是:" + num1 );
    System.out.println( "数字的个数是:" + num2 );
}

java 语言分组实例 (使用正则对象)


@Test
public void ss(){
    Pattern pattern = Pattern. compile ("^(\\d{3,4})\\-(\\d{6,8})$") ;
    Matcher matcher = pattern . matcher ("010-12345678") ;
    if (matcher . matches () ){
        String whole = matcher . group(0); // "010-12345678". 0表示匹配的整个字符串
        string areaCode = matcher. group(1); // "010",1表示匹配的第1个子串
        String telNumber = matcher. group(2); // "12345678", 2表示匹配的第2个子串
    }
}

java 中文查找与替换(使用String方法)

@Test
public void d() {
    String a = "我的世是界是圆的1234567";
    String regexStr = "[\u4E00-\u9FA5]*\\d*";
    if (a.matches( regexStr )) {
        a = a.replace( '是', '-' );
        System.out.println( a );
    }

}

java 清洗数据(使用String方法)


@Test
public void add() {
    String s ="a.b。1.2A";
    String[] split = s.split( "\\.|。|A$" );
    String s1 = Arrays.toString( split );
    System.out.println(s1);
}

附录:

正则在LInux 中的使用推荐陈思齐博客

https://www.cnblogs.com/chensiqiqi/p/6285060.html

本文有借鉴廖雪峰教学B站教学视频
https://www.bilibili.com/video/av74394062?from=search&seid=631167244202567059

posted @ 2020-03-22 02:46  庭有奇树  阅读(172)  评论(0编辑  收藏  举报