java正则表达式四种常用的处理方式(匹配、分割、替代、获取)
例子
1,分割:
@Test public void testDivision() { String s = "锄禾日当午,汗滴禾下土"; String[] sArray = s.split("(?<=\\G.{2})"); List<String> list = Arrays.asList(sArray); System.out.println(list.toString()); //输出:[锄禾, 日当, 午,, 汗滴, 禾下, 土] }
2,匹配:
@Test public void testMatch() { String value="15700098756"; Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"); Matcher m = p.matcher(value); System.out.println(m.matches());//boolean }
3,替换:
@Test public void testReplace() { String s = "锄禾123日当午1,2汗滴禾下土123"; String ss = s.replaceAll("[0-9]", "0"); System.out.println(ss); //输出:锄禾000日当午0,0汗滴禾下土000 }
4,获取:
@Test public void testString() { String s = "A8760X12YY3T"; // 把要匹配的字符串写成正则表达式,然后要提取的字符使用括号括起来 // 在这里,我们要提取最后一个数字,正则规则就是“一个数字加上大于等于0个非数字再加上结束符” Pattern pattern = Pattern.compile("(\\d)[^\\d]*$"); Matcher matcher = pattern.matcher(s); if(matcher.find()) System.out.println(matcher.group(1)); //输出:3 }
if you want to go fast,go alone,if you want to go far,go together