• 正则表达式在Java中的使用


    正则表达式在Java中的使用不仅限于String类中的match()方法!!!

    正则中的^与$

    首先我们来了解这两个符号在正则表达式中的作用:

    ^ 符号放在表达式头部表示开始匹配
    $符号放在尾部表示结束匹配
    如果同时携带^与$符,表示整体匹配,$后面如果再携带其他东西,是会匹配失败的

    整体匹配失败

    如果不携带$则表示部分部分匹配,如图:

    结论:以$结尾的正则只能匹配一个字符串,反之可以匹配多个字符串。

    String的matches方法与上文的异同

    来看这几组匹配结果:

    java
    String regular = "^/(?[^/]+)/(?[^/]+)/pattern$";
    String example = "/org/app/pattern";
    System.out.println(example.matches(regular));//true
    java
    String regular = "^/(?[^/]+)/(?[^/]+)/pattern$";
    String example = "/org/app/pattern123";
    System.out.println(example.matches(regular));//false
    java
    String regular = "^/(?[^/]+)/(?[^/]+)/pattern";
    String example = "/org/app/pattern123";
    System.out.println(example.matches(regular));//false

    与上文中正则匹配的异同就在于,当没有$结尾的时候,正常的正则匹配显示的是部分匹配。而Spring中的match方法给出的匹配结果是false。所以如果遇到这种场景,使用String的match方法很有可能出问题

    Java中的Pattern

    使用Pattern编译正则表达式之后再进行match就可以规避String中match方法出现的问题,直接看代码

    java
    String regular = "^/(?[^/]+)/(?[^/]+)/pattern";
    String example = "/org/app/pattern123";
    System.out.println(example.matches(regular));//false
    
    Pattern compile = Pattern.compile(regular);
    Matcher matcher = compile.matcher(example);
    boolean isMatch = matcher.find();
    System.out.println(isMatch);//true

    使用group方法来提取匹配结果

    java
    String regular = "^/(?[^/]+)/(?[^/]+)/pattern";
    String example = "/org/app/pattern123";
    System.out.println(example.matches(regular));//false
    
    Pattern compile = Pattern.compile(regular);
    Matcher matcher = compile.matcher(example);
    boolean isMatch = matcher.find();
    System.out.println(isMatch);//true
    System.out.println(matcher.group(0));// /org/app/pattern
    System.out.println(matcher.group(1));//org
    System.out.println(matcher.group(2));//app
    System.out.println(matcher.group("app"));//app
    System.out.println(matcher.group("org"));//org

    __EOF__

  • 本文作者: Morning Bell
  • 本文链接: https://www.cnblogs.com/MorningBell/p/16644387.html
  • 关于博主: 古之立大事者,不惟有超世之才,亦必有坚忍不拔之志。
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC-BY-NC-SA 许可协议。转载请注明出处!
  • 声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。
  • 相关阅读:
    Java中的线程池
    BFS广度优先
    后端-打开抖音互联网会发生什么
    01-论文阅读-Deep learning for anomaly detection in log data: a survey
    【Unity每日一记】如何在Unity里面添加视频,做媒体屏幕
    MySQL-存储引擎
    Unity——利用Mesh绘制图形
    android:mediaPlayer.setLooping(true);解决只循环一次
    java中对象的比较
    6 Ajax & JSON
  • 原文地址:https://www.cnblogs.com/MorningBell/p/16644387.html