Java移除/替换 匹配正则表达式的子字符串

  1.         String x="16+(7×17)-90×23+(1÷2)"; 
  2.         StringBuffer operatorStr=new StringBuffer(x);  
  3.           
  4.         // 1.创建 Pattern 对象  
  5.         Pattern p = Pattern.compile("\\d+(\\.\\d*)*");  //匹配数字的正则表达式
  6.         //2.创建Matcher对象  
  7.         Matcher m = p.matcher(operatorStr);  
  8.         int count = 0;  
  9.         while(m.find()) {  
  10.             //find()尝试查找与该模式匹配的输入序列的下一个子序列  
  11.             System.out.println(m.group(0));  
  12.             operatorStr.replace(m.start(), m.end(), "");  
  13.             System.out.println(operatorStr);  
  14.             m = p.matcher(operatorStr);  //更新Matcher对象,指向新字符串的匹配
  15.         }  

目的:移除字符串中的数字

输出:

好吧str.replaceAll(regex, string)方法可以直接实现。我傻了,弄复杂了

猜你喜欢

转载自blog.csdn.net/Nfboys/article/details/82531547
今日推荐