• Java-正则使用


    Java-正则使用

    注意

    在Java中由于string的设计,导致斜杠是特殊的字符,所以如若想要在正则中使用斜杠,则需要两个斜杠来表示

    eg: d 需要写成: \d ,两外 \\ 表示匹配单个斜杠

    需要用到的两个类:

    • java.util.regex.Pattern 模式类:用来表示一个编译过的正则表达式
    • java.util.regex.Matcher 匹配类:用模式匹配一个字符串所得到的结果

    1.判断字符串是否满足正则的两种方式

    //判断字符串是否满足正则的两种方式
    boolean b1= Pattern.matches("正则表达式","字符串"); //判断是否匹配(整个字符串)
    boolean b2= "需要判断的字符串".matches("正则表达式");
    

    2.替换:

    	String regular="dog"; //正则
        String str="This is dog1 dog2  dog3";
                    
        Pattern pattern = Pattern.compile(regular);
        Matcher matcher=pattern.matcher(str);
        str= matcher.replaceAll("cat"); // 替换所有
        str= matcher.replaceFirst("cat"); //替换第一个
    

    3.获取匹配结果

    Pattern pattern = Pattern.compile("正则表达式");
    Matcher matcher=pattern.matcher("需要判断的字符串");
    while (matcher.find()){   //尝试查找与该模式匹配的输入序列的下一个子序列
        String string = matcher.group(1); //获取每个匹配结果分组为1的值
    }
    

    4.Matcher 方法

    start()返回匹配到的子字符串在字符串中的索引位置.

    end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.

    group()返回匹配到的子字符串

    matches() 方法用于在文本中匹配正则表达式(匹配整个文本),不能用于查找正则表达式多次出现

    文章部分内容摘自网络和图书,如有侵权,请联系我。
  • 相关阅读:
    [转]IUnkown生命周期管理
    [转] com 基本数据类型
    Centos 7 修改开机等待时间 Alex
    乌班图的安装常用命令 Alex
    Ubuntu切换root用户 Alex
    乌班图开启关闭防火墙 Alex
    Ubuntu远程root用户登录 Alex
    Centos 8 更改为阿里云源 Alex
    LVS调度之搭建NAT模型实现 Alex
    解决挂载mount: wrong fs type, bad option, bad superblock on Alex
  • 原文地址:https://www.cnblogs.com/-Tiger/p/7421756.html
Copyright © 2020-2023  润新知