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

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

 

 

 

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