字符串截取的一些技巧(待完善)

1、處理字符串用正則匹配最後四位爲2018的字符並刪除

正則:\\d{4}\\s*?(?:\\n|$)          //   代碼中"\\"爲轉譯

//去末尾的方法
public String removeLastPunc(String str){
Matcher m=Pattern.compile("(.*)(2018)$").matcher(str);
if(m.find()){
str=str.replace(m.group(), m.group(1));
}
String removeLastPunc=str;
return removeLastPunc;

}

2、截取字符串中間的字符&去掉指定字符

例如:

String str ="今天星期五,明天不上班!"

用RegexUtil.findFirst("(今天)(\\S+)(,明天)",str ,2)來截取 "星期五"。(需要下載RegexUtil這個工具包)

String strLast=RegexUtil.findFirst("(今天)(\\S+)(,明天)",str,2);

System.out.System.out.println(strLast);

也可以用下面的方法:

String str="1:商戶名稱:湖北白圭企業服務有限公司    商戶號:898440373923713"

表達式:  ((?![商戶名稱:]).)*公司  

截取公司名稱:湖北白圭企業服務有限公司  

String pattern = "((?![商戶名稱:]).)*公司";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(cell.toString());
if (m.find()) {
    merchantInfo.setMerchantName(m.group());
}

Replace &ReplaceAll 的效果不一樣

Replace 除去指定字符或替換  eg: replace("不上班","要加班");|| eg: replace("!","");

ReplaceAll  可以這樣使用      eg: ReplaceAll("星期五.*","");  一樣的可以替換 不同的是ReplaceAll  如果寫"XX.*"會替換XX後面的所有字符爲其他的字符或空;

3、判斷字串中一個字符同時出現的次數

可以使用 apache commons-lang3 jar  

org.apache.commons.lang3.StringUtils.countMatches(CharSequence, CharSequence) 方法

    public static void main(String[] args){
        //看看這個字符串 e 出現的次數
        String str = "feitianbenyue";
        String t = "e";
 
        System.out.println(StringUtils.countMatches(str, t));
    }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章