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;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM