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)來截取 "星期五"。
String strLast=RegexUtil.findFirst("(今天)(\\S+)(,明天)",str,2);
System.out.System.out.println(strLast);
Replace &ReplaceAll 的效果不一樣
Replace 除去指定字符或替換 eg: replace("不上班","要加班");|| eg: replace("!","");
ReplaceAll 可以這樣使用 eg: ReplaceAll("星期五.*",""); 一樣的可以替換 不同的是ReplaceAll 如果寫"XX.*"會替換XX後面的所有字符爲其他的字符或空;