繁体   English   中英

在 Java 中的第 n 次和第 n+1 次出现之间替换字符串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM