我想用一个空字符串替换单个出现的正斜杠(/)。如果正斜杠(/)后接多个正斜杠(/),我只想用空字符串替换第一个斜杠。
样本输入:
情况1:
input: "This is /text/"
output: "This is text"
案例2:
input: "This// is //text"
output: "This/ is /text"
通过使用正则表达式,我们如何在Java中进行替换。
通过捕获第一个斜杠之后,我们可以简单地用捕获组替换一串正斜杠,即搜索
/(/*)
并替换为
$1
在Java中:
String input = "This is /text/";
System.out.println(input.replaceAll("/(/*)", "$1"));
input = "This// is //text";
System.out.println(input.replaceAll("/(/*)", "$1"));
输出:
This is text
This/ is /text