[英]Replace String in between nth and n+1 occurrence of a character in Java
我有一個格式為 abc_1234_01233456_DC 的字符串。 我們如何用其他文本替換第二次和第三次出現“_”之間的文本。
最終輸出將是 abc_1234_78910_DC。 我嘗試使用以下代碼。
if(StringUtils.isNotEmpty(name)){
List<String> nameList = new ArrayList<>(Arrays.asList(StringUtils.split(name, "_")));
if(nameList.size()==3){
nameList.set(2,"78910");
return StringUtils.join(nameList,"_");
}
}
我們有什么簡單的實現方法嗎?
謝謝,斯里。
更好的方法 - 使用正則表達式
String input = "abc_1234_01233456_DC";
Matcher matcher = Pattern.compile("(_([^_]+)){2}").matcher(input);//{2} - number of occurrence
String result = matcher.find() ? new StringBuilder(input).replace(matcher.start(2), matcher.end(2), "78910").toString() : input; //abc_1234_78910_DC
就是這樣
你可以只用java.lang.String
類來完成。
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getUpdated("abc_1234_01233456_DC", "78910"));
}
static String getUpdated(String name, String replacementStr) {
String parts[] = {};
if (name != null) {
parts = name.split("_");
if (parts.length > 3) {
parts[2] = replacementStr;
}
}
return String.join("_", parts);
}
}
輸出:
abc_1234_78910_DC
您還可以參數化分隔符和要替換的部分/字號,例如
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getUpdated("abc_1234_01233456_DC", "78910", "_", 3));
}
/**
* Replaces the nth part/word and returns the updated string
*
* @param str - The string to be updated
* @param replacementStr - The replacement string
* @param delimiter - The delimiter to split the string on
* @param nth - The part/word to be replaced
* @return the updated string
*/
static String getUpdated(String str, String replacementStr, String delimiter, int nth) {
String parts[] = {};
if (str != null) {
parts = str.split(Pattern.quote(delimiter), nth + 1);
if (parts.length > nth) {
parts[nth - 1] = replacementStr;
}
}
return String.join(delimiter, parts);
}
}
輸出:
abc_1234_78910_DC
只需使用 String 類的 Java 標准 indexOf 方法,您就可以輕松實現您正在尋找的內容:
public static void main(String[] args) {
final String test = "abc_1234_01233456_DC";
final String replacement = "78910";
System.out.println(replace("_", 2, test, replacement));
}
public static String replace(String cue, int occur, String input, String replacement) {
int index = 0;
while (occur-- > 0) {
index = input.indexOf(cue, index);
if (-1 == index) {
return input;
}
index++;
}
int nextIndex = input.indexOf(cue, index);
if (-1 == nextIndex) {
nextIndex = input.length();
}
return input.substring(0, index) + replacement + input.substring(nextIndex);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.