如何用另一个词替换三个斜线后的词?

how to replace a word after three slash with another word?

我有一个字符串,我需要用另一个词替换其中的一个词。这是我的字符串 clientId 作为 /qw/ty/s11/dc3/124,我有另一个字符串 id 作为 p13。我想用 p13 替换 clientId 字符串中的 s11

clientId 的格式将始终完全相同。意思是总是会有三个斜杠 / 之后我需要用另一个词替换那个词所以三个斜杠后的任何词,我需要用 id.

的值替换它
String clientId = "/qw/ty/s11/dc3/124";
String id = "p13";
String newId = ""; // this should come as /qw/ty/p13/dc3/124

执行此操作的简单方法是什么?

您可以使用indexOf 方法搜索第二个斜杠。你必须这样做 3 次。返回的 3 位置将是您想要的位置。既然你说的是立场永远不会改变,那就是如何做到这一点的场景。另一种方法是使用 split 方法拆分字符串。然后你将不得不遍历它并只替换第三个单词。对于每次迭代,您还必须使用 StringBuilder 连接 String 以获得返回路径。这两种方法将不使用 REGEX 值。第三种选择是,就像有人建议的那样,使用 REGEX。

我做这道题的方法是遍历第一个字符串,直到找到 3 个斜杠,然后将名为 "start" 的变量设置为第三个斜杠的索引。接下来,我从头开始循环,直到找到另一个斜杠,并将一个名为 "end" 的变量设置为索引。之后我用string replace方法把start+1到end的子串替换成新的id。这是代码:

String clientId = "/qw/ty/s11/dc3/124";
    String id = "p13";
    String newId = "";
    String temporaryID = clientId;
    int slashCounter = 0;
    int start = -1; //Will throw index exception if clientId format is wrong
    int end = -1; //Will throw index exception if clientId format is wrong
    for(int i = 0; i < temporaryID.length(); i++){
        if(temporaryID.charAt(i)=='/') slashCounter++;
        if(slashCounter==3){
            start = i;
            break;
        }
    }
    for(int i = start + 1; i < temporaryID.length(); i++){
        if(temporaryID.charAt(i)=='/') end = i;
        if(end!=-1) break;
    }
    newId = temporaryID.replace(temporaryID.substring(start+1, end), id);
    System.out.println(newId);

如果您需要替换第 3 和第 4 个斜杠之间的单词,请尝试此操作

        int counter = 0;
        int start=0;
        int end = clientId.length()-1;
        for (int i = 0; i < clientId.length(); i++) {
            if (clientId.charAt(i) == '/') {
                counter++;
                if (counter == 3) {
                    start = i+1; // find the index of the char after the 3rd slash
                } else if (counter == 4) {
                    end = i; // find the index of the 4th slash
                    break;
                }
            }
        }
        String newId = clientId.substring(0, start) + id + clientId.substring(end);

或者如果你想替换第三个斜杠后的所有内容:

String newId = clientId.substring(0, start) + id; 

您绝对可以借助正则表达式更改字符串的任何部分。

尝试:

String content = "/qw/ty/xx/dc3/124";
String replacement = "replacement";

Pattern regex = Pattern.compile("((?:/[^/]+){2}/)([^/]*)(\S*)", Pattern.MULTILINE);

Matcher matcher = regex.matcher(content);
if(matcher.find()){
    String result = matcher.replaceFirst("" + replacement + "");
    System.out.println(result);
}

基于输入字符串和替换值,它将发出:

/qw/ty/replacement/dc3/124 

您可以尝试使用此正则表达式来查找第三个和第四个斜杠之间的字符串,即您的 ID 并进行替换。

正则表达式: (\/.*?\/.*?\/).*?\/

Regex101 Demo