zoukankan      html  css  js  c++  java
  • 正则表达式在Java中应用的三种典型场合:验证,查找和替换

    正则式在编程中常用,总结在此以备考:

    package regularexp;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RegUsages {
    // 验证例子
    private static boolean verify(String code) { final String patternStr = "\d+"; return Pattern.matches(patternStr, code); } // 查找例子 private static void search() { Pattern pattern = Pattern.compile("m(o+)n", Pattern.CASE_INSENSITIVE); Matcher matcher=pattern.matcher("Sun Earth moon mooon Mon mooooon Mooon Mars"); while(matcher.find()) { System.out.println(String.format("%s (%d~%d)", matcher.group(0),matcher.start(),matcher.end())); } } // 更替例子1 private static void replace1() { String str = "10元 1000人民币 10000元 100000RMB"; str = str.replaceAll("(\d+)(元|人民币|RMB)", "$1圆"); System.out.println(str); } // 更替例子2 private static void replace2() { Pattern p = Pattern.compile("m(o+)n", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher("Sun Earth moon mooon Mon mooooon Mooon Mars"); StringBuffer sb = new StringBuffer(); boolean result = m.find(); while (result) { m.appendReplacement(sb, "Moon"); result = m.find(); } m.appendTail(sb); System.out.println("Result=" + sb.toString()); } public static void main(String[] args) { System.out.println(String.format("601857 %s a stock code.",verify("601857")?"is":"isn't")); search(); replace1(); replace2(); } }

    输出:

    601857 is a stock code.
    moon (10~14)
    mooon (15~20)
    Mon (21~24)
    mooooon (25~32)
    Mooon (33~38)
    10圆 1000圆 10000圆 100000圆
    Result=Sun Earth Moon Moon Moon Moon Moon Mars

    --2020-03-06--

  • 相关阅读:
    jsp内置对象
    Response响应
    中医不传之秘
    slam-四元运动学
    ubuntu 16.04 设置 win+e 快捷键打开文件夹管理器
    ubuntu16.04 更新nvidia 显卡驱动后显示 clean ... files ... blocks ... /sys/class/backlight/nvidia_0/actural_brightness
    android studio 引入模块失败解决方法
    gradle
    python logger
    ubuntu自定义终端风格
  • 原文地址:https://www.cnblogs.com/heyang78/p/12424725.html
Copyright © 2011-2022 走看看