轉:
@Test
public void test33() { String phoneString = "哈哈,13888889999"; // 提取數字 // 1 Pattern pattern = Pattern.compile("[^0-9]"); Matcher matcher = pattern.matcher(phoneString); String all = matcher.replaceAll(""); System.out.println("phone:" + all); // 2 Pattern.compile("[^0-9]").matcher(phoneString).replaceAll(""); }
@Test
public void test() { // 提取張三 去除數字 String r_name3 = "張三 13599998888 000000"; Pattern pattern = Pattern.compile("[\\d]"); Matcher matcher = pattern.matcher(r_name3); System.out.println(matcher.replaceAll("").trim()); }
需求:過濾除點號外的所有非數字:
String abc = "價格:0.00元";
Pattern compile = Pattern.compile("\\d+\\.\\d+"); Matcher matcher = compile.matcher(abc); matcher.find(); String string = matcher.group();//提取匹配到的結果 System.out.println(string);//0.00
需求:只要提取數字其它都不需要
String abc = "手機:1319999999";
System.out.println(abc.replaceAll("\\D", ""));//1319999999
需求:提取價格出來
package com.infomorrow.parser_datasource; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; public class test_money { @Test 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()); } }