首页 > 其他分享 >正则表达式:

正则表达式:

时间:2024-04-06 20:13:30浏览次数:28  
标签:false 正则表达式 System matches println out

Java正则表达式:

一,什么是正则表达式?

正则表达式是由一些特殊字符组成的,代表某一种规则的表达式;例如:"[abc]"表示单个字符只能是‘a’,‘b’,‘c’中的一个;

有什么用处?

正则表达式主要用于文本格式分析;如:校验数据的格式,查找文本中想要的内容;

二,正则表达式有哪些?

String中有一个匹配正则表达式的方法:

这个方法是用来匹配一个字符串是否匹配正则表达式的规则,参数需要调用者传递一个正则表达式。但是正则表达式不能乱写,是有特定的规则的。在API中有一个类叫做Pattern,我们可以到API文档中搜索,关于正则表达式的规则,这个类都告诉我们了。

三,以下演示以下常见基本用法
/**
 * 目标:掌握正则表达式的书写规则
 */
public class RegexTest2 {
    public static void main(String[] args) {
        // 1、字符类(只能匹配单个字符)
        System.out.println("a".matches("[abc]"));    // [abc]只能匹配a、b、c
        System.out.println("e".matches("[abcd]")); // false

        System.out.println("d".matches("[^abc]"));   // [^abc] 不能是abc
        System.out.println("a".matches("[^abc]"));  // false

        System.out.println("b".matches("[a-zA-Z]")); // [a-zA-Z] 只能是a-z A-Z的字符
        System.out.println("2".matches("[a-zA-Z]")); // false

        System.out.println("k".matches("[a-z&&[^bc]]")); // : a到z,除了b和c
        System.out.println("b".matches("[a-z&&[^bc]]")); // false

        System.out.println("ab".matches("[a-zA-Z0-9]")); // false 注意:以上带 [内容] 的规则都只能用于匹配单个字符

        // 2、预定义字符(只能匹配单个字符)  .  \d  \D   \s  \S  \w  \W
        System.out.println("徐".matches(".")); // .可以匹配任意字符
        System.out.println("徐徐".matches(".")); // false

        // \转义
        System.out.println("\"");
        // \n \t,需要注意这里做为参数传递时本身带有\的要在前面加上\做转义
        System.out.println("3".matches("\\d"));  // \d: 0-9
        System.out.println("a".matches("\\d"));  //false

        System.out.println(" ".matches("\\s"));   // \s: 代表一个空白字符
        System.out.println("a".matches("\s")); // false

        System.out.println("a".matches("\\S"));  // \S: 代表一个非空白字符
        System.out.println(" ".matches("\\S")); // false

        System.out.println("a".matches("\\w"));  // \w: [a-zA-Z_0-9]
        System.out.println("_".matches("\\w")); // true
        System.out.println("徐".matches("\\w")); // false

        System.out.println("徐".matches("\\W"));  // [^\w]不能是a-zA-Z_0-9
        System.out.println("a".matches("\\W"));  // false

        System.out.println("23232".matches("\\d")); // false 注意:以上预定义字符都只能匹配单个字符。

        // 3、数量词: ?   *   +   {n}   {n, }  {n, m}
        System.out.println("a".matches("\\w?"));   // ? 代表0次或1次;\w	一个字字符:
        [a-zA-Z_0-9]意思为单个字符且只能出现1次或0次
        System.out.println("".matches("\\w?"));    // true
        System.out.println("abc".matches("\\w?")); // false

        System.out.println("abc12".matches("\\w*"));   // * 代表0次或多次
        System.out.println("".matches("\\w*"));        // true
        System.out.println("abc12张".matches("\\w*")); // false

        System.out.println("abc12".matches("\\w+"));   // + 代表1次或多次
        System.out.println("".matches("\\w+"));       // false
        System.out.println("abc12张".matches("\\w+")); // false

        System.out.println("a3c".matches("\\w{3}"));   // {3} 代表要正好是n次
        System.out.println("abcd".matches("\\w{3}"));  // false
        System.out.println("abcd".matches("\\w{3,}"));     // {3,} 代表是>=3次
        System.out.println("ab".matches("\\w{3,}"));     // false
        System.out.println("abcde徐".matches("\\w{3,}"));     // false
        System.out.println("abc232d".matches("\\w{3,9}"));     // {3, 9} 代表是  大于等于3次,小于等于9次

        // 4、其他几个常用的符号:(?i)忽略大小写 、 或:| 、  分组:()
        System.out.println("abc".matches("(?i)abc")); // true
        System.out.println("ABC".matches("(?i)abc")); // true
        System.out.println("aBc".matches("a((?i)b)c")); // true
        System.out.println("ABc".matches("a((?i)b)c")); // false

        // 需求1:要求要么是3个小写字母,要么是3个数字。
        System.out.println("abc".matches("[a-z]{3}|\\d{3}")); // true
        System.out.println("ABC".matches("[a-z]{3}|\\d{3}")); // false
        System.out.println("123".matches("[a-z]{3}|\\d{3}")); // true
        System.out.println("A12".matches("[a-z]{3}|\\d{3}")); // false

        // 需求2:必须是”我爱“开头,中间可以是至少一个”编程“,最后至少是1个”666“
        System.out.println("我爱编程编程666666".matches("我爱(编程)+(666)+"));
        System.out.println("我爱编程编程66666".matches("我爱(编程)+(666)+"));
    }
}
四,以下拓展几个正则表达式的常用场景和案例:
1.正则表达式校验手机号码:
/**
 * 目标:校验用户输入的电话、邮箱、时间是否合法。
 */
public class RegexTest3 {
    public static void main(String[] args) {
        checkPhone();
    }

    public static void checkPhone(){
        while (true) {
            System.out.println("请您输入您的电话号码(手机|座机): ");
            Scanner sc = new Scanner(System.in);
            String phone = sc.nextLine();
            // 18676769999  010-3424242424 0104644535
            if(phone.matches("(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})")){
                System.out.println("您输入的号码格式正确~~~");
                break;
            }else {
                System.out.println("您输入的号码格式不正确~~~");
            }
        }
    }
}
2.使用正则表达式校验邮箱是否正确:
public class RegexTest3 {
    public static void main(String[] args) {
        checkEmail();
    }

    public static void checkEmail(){
        while (true) {
            System.out.println("请您输入您的邮箱: ");
            Scanner sc = new Scanner(System.in);
            String email = sc.nextLine();
            /**
             * [email protected]
             * [email protected]
             * [email protected]
             * [email protected]
             */
            //  首先判断两个字符至少是[a-zA-Z_0-9],
  		  //一定存在@,且@后面有2-20个字符[a-zA-Z_0-9],然后后面跟1-2个("."且后面必须跟2-10个字符[a-zA-Z_0-9])这一坨;  
            if(email.matches("\\w{2,}@\\w{2,20}(\\.\\w{2,10}){1,2}")){
                System.out.println("您输入的邮箱格式正确~~~");
                break;
            }else {
                System.out.println("您输入的邮箱格式不正确~~~");
            }
        }
    }
}

3.正则表达式信息爬取:

/**
 * 目标:掌握使用正则表达式查找内容。
 */
public class RegexTest4 {
    public static void main(String[] args) {
        method1();
    }

    // 需求1:从以下内容中爬取出,手机,邮箱,座机、400电话等信息。
    public static void method1(){
        String data ="        电话:1866668888,18699997777\n" +
                "        或者联系邮箱:[email protected],\n" +
                "        座机电话:01036517895,010-98951256\n" +
                "        邮箱:[email protected],\n" +
                "        邮箱:[email protected],\n" +
                "        热线电话:400-618-9090 ,400-618-4000,4006184000,4006189090";
        // 1、定义爬取规则
        String regex = "(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})|(\\w{2,}@\\w{2,20}(\\.\\w{2,10}){1,2})"
                + "|(400-?\\d{3,7}-?\\d{3,7})";
        // 2、把正则表达式封装成一个Pattern对象
        Pattern pattern = Pattern.compile(regex);
        // 3、通过pattern对象去获取查找内容的匹配器对象。
        Matcher matcher = pattern.matcher(data);
        // 4、定义一个循环开始爬取信息
        while (matcher.find()){
            String rs = matcher.group(); // 获取到了找到的内容了。
            System.out.println(rs);
        }
    }
}
4.正则表达式搜索、替换:

这几个功能需要用到Stirng类中的方法。

/**
 * 目标:掌握使用正则表达式做搜索替换,内容分割。
 */
public class RegexTest5 {
    public static void main(String[] args) {
        // 1、public String replaceAll(String regex , String newStr):按照正则表达式匹配的内容进行替换
        // 需求1:请把下面字符串中的不是汉字的部分替换为 “-”
        String s1 = "古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
        System.out.println(s1.replaceAll("\\w+", "-"));
        
        // 需求2(拓展):某语音系统,收到一个口吃的人说的“我我我喜欢编编编编编编编编编编编编程程程!”,需要优化成“我喜欢编程!”。
        String s2 = "我我我喜欢编编编编编编编编编编编编程程程";
        System.out.println(s2.replaceAll("(.)\\1+", "$1"));

        // 2、public String[] split(String regex):按照正则表达式匹配的内容进行分割字符串,反回一个字符串数组。
        // 需求1:请把下面字符串中的人名取出来,使用切割来做
        String s3 = "古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
        String[] names = s3.split("\\w+");
        System.out.println(Arrays.toString(names));
    }
}
正则表达式在工作中应用场景是有的,正则表达式本身较多实在记不住可以在网上找写好的模板,如:需要手机号的正则表达式即可在搜索软件上搜索相关。爬取信息的方式我们平常开发也会经常会遇到需要从字符串数据中找我们需要的信息的情况,在没有第三方资源库的情况下使用正则表达式是不错的选择

标签:false,正则表达式,System,matches,println,out
From: https://www.cnblogs.com/qianshibooks/p/18117842

相关文章

  • Go 正则表达式学习
    正则是用于处理文本的利器之一。关于正则的基础知识及应用,之前写过几篇文章,读者可以阅读文后的相关资料作一基本了解。本文主要学习Go的正则。正则表达式学习,可以分为三个子部分:正则API;正则语法;正则匹配策略。正则API第一个要学习的,就是Go正则API。API是通往......
  • Java | Leetcode Java题解之第10题正则表达式匹配
    题目:题解:classSolution{publicbooleanisMatch(Strings,Stringp){intm=s.length();intn=p.length();boolean[][]f=newboolean[m+1][n+1];f[0][0]=true;for(inti=0;i<=m;++i){......
  • C++11中的正则表达式
    目录regexregex_match函数详解函数原型使用方法基本使用使用std::smatch获取更多信息注意事项regex_search函数详解函数原型使用方法基本使用使用std::smatch获取匹配信息注意事项regex_search和regex_match的区别regexC++11引入了<regex>头文件,它提供了对正则表达式的......
  • linux正则表达式之*
    1.*含义linux正则表达式*表示重复0个或多个前一个重复字符2.样例正则表达式*样例命令:grep-n"min*"anaconda-ks.cfg#找出含有mi、min、minn等字符串的行。注:因为*可以是0个,所以mi也是符合搜索字符串,另外,因为*为重复前一个字符的符号,因此,在*之前必须要紧挨着一个重复字......
  • 正则表达式
    正则表达式正表达式分类:正则表达式:REGEXP,REGularEXPression。正则表达式分为两类:BasicREGEXP(基本正则表达式)ExtendedREGEXP(扩展正则表达式)正则表达式定义:正则表达式(RegularExpression,通常简写为regex、regexp或RE)是一种文本模式,用于描述和匹配一系列符合某个......
  • JavaScript快速入门笔记之七(String:字符串类型、RegExp:正则表达式)
    JavaScript快速入门笔记之七(String:字符串类型、RegExp:正则表达式)String:字符串类型什么是字符串?底层本质:一串字符组成的只读字符数组包装类型:临时封装原始类型数据,并提供对数据操作方法的对象——类型名和原始类型名相同!StringNumberBoolean何时使用:不必手动创建!......
  • notepad++ 利用正则表达式批量删除关键词所在行
    摘要平时使用notepad++查看文本文档,或者打开日志文件,总有一些不太关心的信息需要去除,基于这种情况,notepad++支持正则表达式,便有了操作空间。正则表达式查找使用正则表达式#匹配指定关键字所在的整行^.*关键字.*\r?\n示例:匹配包含"info"的行^.*info.*\r?\n具体步骤使用......
  • 正则表达式的贪婪模式与非贪婪模式
    正则表达式中的贪婪模式和非贪婪模式(也称为勉强模式或懒惰模式)是量词行为的两种不同模式。这些模式影响正则表达式如何匹配字符串中的字符序列。贪婪模式(Greedy)贪婪模式是正则表达式的默认行为。在贪婪模式下,正则表达式会尽可能多地匹配字符。它会尝试匹配尽可能长的字符串片......
  • 16使用正则表达式处理字符串
    1<!DOCTYPEhtml>2<htmllang="en">3<head>4<metacharset="UTF-8">5<metaname="viewport"content="width=device-width,initial-scale=1.0">6<title>Document......
  • 正则表达式
    字符描述\将下一个字符标记为一个特殊字符、或一个原义字符、或一个向后引用、或一个八进制转义符。例如,“n”匹配字符“n”。“\n”匹配一个换行符。串行“\\”匹配“\”而“\(”则匹配“(”。^匹配输入字符串的开始位置。如果设置了RegExp对象的Multiline属性,^也匹......