如果正斜杠(/)后接多个正斜杠,则每次出现时仅替换第一个斜杠

问题描述 投票:0回答:1

我想用一个空字符串替换单个出现的正斜杠(/)。如果正斜杠(/)后接多个正斜杠(/),我只想用空字符串替换第一个斜杠。

样本输入:

情况1:

input: "This is /text/"
output: "This is text"

案例2:

input: "This// is //text"
output: "This/ is /text"

通过使用正则表达式,我们如何在Java中进行替换。

java regex
1个回答
1
投票

通过捕获第一个斜杠之后,我们可以简单地用捕获组替换一串正斜杠,即搜索

/(/*)

并替换为

$1

Demo on regex101

在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
© www.soinside.com 2019 - 2024. All rights reserved.