相关文章推荐
欢快的创口贴  ·  c++ - Member ...·  1 年前    · 
怕考试的苹果  ·  json - await vs ...·  1 年前    · 
机灵的炒面  ·  Feed Item Detail | ...·  1 年前    · 
public void test01(){ String str1 = " 应收:12;实收:100;找零:88 " ; String pattern2 = " 找零:(\\d+)(.*) " ; // String pattern2 = "\\S+:(\\d+)(.*);"; // String pattern2 = "\\S+:(\\d+)(.*)"; // 创建 Pattern 对象 Pattern r2 = Pattern.compile(pattern2); // 现在创建 matcher 对象 Matcher m2 = r2.matcher(str1); if (m2.find()) { System. out .println( " m.group(0) = " + m2.group( 0 )); System. out .println( " m.group(1) = " + m2.group( 1 )); } else { System. out .println( " NO MATCH1 " );

m.group(0) = 找零:88
m.group(1) = 88

找到group(1) 可以使用了

二、匹配指定字符串

  @Test
    private  void  matchText(){
        String foodRemark = "口味:免辣,微辣,测试的口味;做法:次加糖,啊加双蛋,博香菜,虾皮; 这是其它备注,最后位置";
        String handleFoodRemark=getTextFromFoodRemark(foodRemark,"\\做法:(.*?)\\;");
        System.out.println("handleFoodRemark = " + handleFoodRemark);        
public static String getTextFromFoodRemark(String foodRemark, String regex) {
        Pattern pattern = Pattern.compile(regex);// 匹配的模式
        Matcher m = pattern.matcher(foodRemark);
        if (m.find()) {
            return m.group(1);//取第一族匹配的字符串
        return "";

输出结果:次加糖,啊加双蛋,博香菜,虾皮