JAVA正则表达式,按照指定的标记分割和取值

    public static void main(String[] args) {
        String test = "电源:v24值${1}$v12值${2}$,电源:v24值${3}$v12值${4}$";
        String regex = "\\$\\{([.\\s\\S]*?)\\}\\$";
        String[] strings = test.split(regex);
        for (String string : strings) {
            System.out.println(string);
        }


        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(test);
        while(m.find()){
            System.out.println(m.group(0));
            System.out.println(m.group(1));
        }
    }
//这是输出结果
电源:v24值
v12值
,电源:v24值
v12值
${1}$
1
${2}$
2
${3}$
3
${4}$
4

还有更复杂的业务要求

说明一下我需要将“”“”“温度值 80 {80}温度值 {80}温度值 80 {80}”“”“”“”“”这样的字符串以 {}进行拆分,并且保留其中的值

    public static void main(String[] args) {
        String changeString="温度值${80}";
        String regex = "\\$\\{([.\\s\\S]*?)\\}";
        String[] strings = changeString.split(regex);
        //2.2.1.2使用正则表达式对字符串进行拆分
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(changeString);
        //首先判断是否是开始,
        int a=0;//使用了多少个字符串了
        String b="";

        int index=0;
        while(m.find()){
            String editStr = m.group(0);//当前输入框内容
            int editIndex = changeString.indexOf(editStr,index);//当前输入框下标
            if(index==0){
                //判断是否是输入框开头
                if(editIndex==0){
                    b=b+m.group(0);
                    //更新下标
                    index=editIndex+m.group(0).length()-1;
                    continue;
                }else{
                    b=b+strings[a];
                    a++;
                    b=b+m.group(0);
                    index=editIndex+ (strings.length>a+1?strings[a].length():0);
                    continue;
                }
            }
            //判断当前是否是连续的输入框,通过上次的结束下标和这次的开头下标是否相差大于1
            if(editIndex-index>=1){
                if(StringUtil.isEmpty(strings[a])){
                    a++;
                }
                //相差大于1
                //添加文字说明
                b=b+strings[a];
                a++;
                editIndex=editIndex+ (strings.length>a+1?strings[a].length():0);
            }
            //添加输入框
            b=b+m.group(0);
            //更新下标
            index=editIndex+m.group(0).length()-1;
        }
        if(index<changeString.length()-1){
            b=b+(strings.length>a+1?strings[a]:"");
            if(strings.length>a){
                b=b+strings[a];
            }
        }
        System.out.println(b);
    }

猜你喜欢

转载自blog.csdn.net/zhaohan___/article/details/89916865