正则表达式应用

来源:互联网 发布:淘宝手机充值未到账 编辑:程序博客网 时间:2024/06/05 23:00

截取字符串中的数据,获得数字。比如页面获取数据是字符串的价格。

package com.tsy.test;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * Created by Administrator on 2017/6/7. */public class TestRegex {    public static void main(String[] args) {        System.out.println("--" + new TestRegex().extract_cost_dot("CNY3,779"));        System.out.println("--" + new TestRegex().parseNumber("CNY3,779,123,012.15"));    }    public void test(){        //0        //0.1        //24.13        String moneyString="1";        Double extract_cost = extract_cost_dot(moneyString);        System.out.println("extract_cost:"+extract_cost);    }    /**     * 提取金额,规则为只提取数字和点号,必须有点号     * 格式可以为0.0或者,11     * @param cost     * @return     */    public   Double extract_cost_dot(String cost) {        Pattern compile = Pattern.compile("(\\d+\\.\\d+)|(\\d+)");        Matcher matcher = compile.matcher(cost);        matcher.find();        return Double.valueOf(matcher.group());    }    /**     * 去除字符串中的【非数字及小数点】的其他字符     * @param str     * @return     */    public static String parseNumber(String str){        String tmpStr="";        if(str.length()>0){            for(int i=0;i<str.length();i++){                String tmp=""+str.charAt(i);                if((tmp).matches("[0-9.]")){                    tmpStr+=tmp;                }            }        }        return tmpStr;    }}



1 0