pageHelper 排序 +- 字符串处理

自己记录一下。
前端要把sort参数传过来,

1. 如果约定是下面这种形式:

sort=id-name+age+

直接在java后台进行替换就行,连正则都不用。

sort = sort.replace("-", " desc,").replace("+", " asc,");
sort = sort.substring(0, sort.length() - 1);
PageHelper.startPage(pageNum, pageSize, sort)即可
        

2. 但是,大家好像都是采用类似这样的形式:

sort=+id-name+age

想要把+ - 替换成对应的asc desc就不是那么随便了。
我的方式:

sort = sort.replaceAll("\+([\w]+)", " $1" + " asc,");
sort = sort.replaceAll("\-([\w]+)", " $1" + " desc,");
sort = sort.substring(0, sort.length() - 1);
PageHelper.startPage(pageNum, pageSize, sort)

$1是用来获取前面正则表达式中的第1个小括号中的值的。我的第一个小括号把 减号后面的单词获取到,所以直接拼接asc, 就可以了。
同理,$2是用来获取第2个小括号中的内容的。

3. Demo:

public class Re {
    public static void main(String[] args) throws Exception {
        String a1 = "+id";
        String a2 = "+id-name+age";
        String a3 = "id+name-age";
        symbolReplace(a1);
        symbolReplace(a2);
        symbolReplace(a3);
    }

    public static String symbolReplace(String sort) throws Exception {
        if (!Pattern.matches("((\+|\-)[\w]+)+", sort)) {
//            throw new Exception();自己定义一个格式非法异常,这里抛出去。
        }
        sort = sort.replaceAll("\+([\w]+)", " $1" + " asc,");
        sort = sort.replaceAll("\-([\w]+)", " $1" + " desc,");
        sort = sort.substring(0, sort.length() - 1);
        return sort;
    }
}
原文地址:https://www.cnblogs.com/simuhunluo/p/9266831.html