[英]How to replace all string except specific part in string
我有一個字符串abc____2019____5_10_40_56_20190319213500.pdf
,我想替換date stamp
之前的字符串。
任何人都可以提出建議嗎?
謝謝。
嘿使用時間戳的長度和字符串的長度來處理這個。請我下面的代碼會幫助你
String sample = "abc____2019____5_10_40_56_20190319213500";
int lengthOfTimestamp = 25;
String value = sample.substring(sample.length() -lengthOfTimestamp ,sample.length());
System.out.println("value :"+value);
輸出:
value : 5_10_40_56_20190319213500
不需要正則表達式 :) 只需按最后一次出現的下划線分割整個字符串:
String s = "abc____2019____5_10_40_56_20190319213500.pdf";
s = s.substring(0, s.lastIndexOf("_"));
或者,如果您想之前更換該部件,您可以使用:
String s = "abc____2019____5_10_40_56_20190319213500.pdf";
s = "replacment" + s.substring(s.lastIndexOf("_") + 1);
以下是三種簡單的方法。
非正則表達式方式。 只需使用_
拆分並使用此代碼從數組中獲取最后一項,
String s = "abc____2019____5_10_40_56_20190319213500.pdf";
String[] data = s.split("_");
System.out.println(data[data.length-1]);
印刷,
20190319213500.pdf
正則表達式的方式更酷,只有一個班級代碼。 替換從開始到最后一次出現下划線的所有內容,
String s = "abc____2019____5_10_40_56_20190319213500.pdf";
System.out.println(s.replaceAll("^.*_", ""));
印刷,
20190319213500.pdf
在Matcher
使用find
方法的另一種方法是使用此代碼找到最后一個數字模式,然后是任何非數字模式,直到行尾,
String s = "abc____2019____5_10_40_56_20190319213500.pdf";
Pattern p = Pattern.compile("\\d+\\D*$");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group());
} else {
System.out.println("Didn't find");
}
印刷,
20190319213500.pdf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.