zoukankan      html  css  js  c++  java
  • 【Java/Regexp】用正则去除数字字符串左边多余的零

    代码:

    package test;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * 去掉数字字符串左边多余的0
     * @author hy
     *
     */
    public class Test7 {
        public static void main(String[] args) {
            String[] arr= {"01","001","0001","0001000","040","097018","0651","50001","10000"};
            
            for(String str:arr) {
                String line=String.format("%-10s%s%10s",str,"=>",trimLeftZero(str));
                System.out.println(line);
            }
        }
        
        /**
         * 去掉数字字符串左边多余的0
         * @param numericText
         * @return
         */
        private static String trimLeftZero(String numericText) {
            Pattern pattern = Pattern.compile("^([0]+)([0-9]*)$", Pattern.CASE_INSENSITIVE);
            
            Matcher matcher=pattern.matcher(numericText);
            while(matcher.find()) {
                return matcher.group(2);
            }
            
            return numericText;
        }
    }

    输出:

    01        =>         1
    001       =>         1
    0001      =>         1
    0001000   =>      1000
    040       =>        40
    097018    =>     97018
    0651      =>       651
    50001     =>     50001
    10000     =>     10000

    END

  • 相关阅读:
    理解HTTP幂等性
    企业技术树
    数据库MySQL-Oracle-DB2-SQLServer分页查询
    Redis安装教程
    Redis VS Memcached
    Redis简介
    Redis系列文章导读
    坐标轴
    图例
    画网格
  • 原文地址:https://www.cnblogs.com/heyang78/p/15746974.html
Copyright © 2011-2022 走看看