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

sqougxex  于 2021-07-13  发布在  Java
关注(0)|答案(5)|浏览(259)

我有一个字符串,其中我需要用另一个词替换一个词。这是我的绳子 clientId 作为 /qw/ty/s11/dc3/124 我还有一根绳子 id 作为 p13 . 我想替换 s11clientId 字符串 p13 .
格式 clientId 总是一样的。意味着会有三个slah / 总是在这之后,我需要用另一个词替换这个词,所以三个斜杠之后的任何词,我都需要用 id .

String clientId = "/qw/ty/s11/dc3/124";
String id = "p13";
String newId = ""; // this should come as /qw/ty/p13/dc3/124

最简单的方法是什么?

niwlg2el

niwlg2el1#

在正则表达式的帮助下,你完全可以改变字符串的任何部分。
尝试:

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("$1" + replacement + "$3");
    System.out.println(result);
}

根据输入字符串和替换值,它将发出:

/qw/ty/replacement/dc3/124
8tntrjer

8tntrjer2#

你可以用 indexOf 方法来搜索第二个斜杠。你得做三次。返回的3个位置就是你想要的。既然你说的是位置永远不会改变,那就要考虑怎么做了。另一种方法是用绳子把绳子分开 split 方法。然后你必须遍历它,只替换第三个单词。对于每个迭代,您还必须使用 StringBuilder 连接 String 为了找到回去的路。这两种方法不需要使用regex值。第三种选择是,像有人建议的那样,使用regex。

h79rfbju

h79rfbju3#

我解决这个问题的方法是在第一个字符串中循环,直到找到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);
o7jaxewo

o7jaxewo4#

如果您需要替换第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;
tuwxkamq

tuwxkamq5#

您可以尝试使用这个正则表达式来查找第三个和第四个斜杠之间的字符串,这是您的id,并进行替换。
正则表达式: (\/.*?\/.*?\/).*?\/ regex101演示

相关问题