zoukankan      html  css  js  c++  java
  • 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() 方法用于在文本中匹配正则表达式(匹配整个文本),不能用于查找正则表达式多次出现

    文章部分内容摘自网络和图书,如有侵权,请联系我。
  • 相关阅读:
    Angular2+学习第1篇 简介
    JS:ES5数组基本操作
    git常用操作命令
    URL-Routing
    uid-datepicker
    元素隐藏 css
    Angular2+学习第2篇 cli 环境搭建过程
    DRF 07
    DRF小练习 04
    DRF小练习 02
  • 原文地址:https://www.cnblogs.com/-Tiger/p/7421756.html
Copyright © 2011-2022 走看看