我有一个字符串,我需要用另一个词替换其中的一个词。这是我的字符串 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
执行此操作的简单方法是什么?
最佳答案
您绝对可以在正则表达式的帮助下更改字符串的任何部分。
尝试:
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
关于java - 如何用另一个词替换三个斜线后的词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36253652/