我需要从给定的字符串中删除结尾的[/]00/
。
示例:
string: '01/00/00/00/00/00/00/' -> 01
string: '01/02/03/00/00/00/00/' -> 01/02/03
string: '10/25/03/56/00/00/00/' -> 10/25/03/56
我一直在为此苦苦挣扎,但我不太想知道如何从[/]
中删除[/]00
。
我的意思是,替换的表达式必须以/
结尾。
我尝试过以下表达式:
\d{2}\/(?=(?:\d{2}\/)+$)
匹配项是:
这让我很困惑...
有什么想法吗?
答案 0 :(得分:0)
您可以使用正则表达式/00|(?<=(00))/
,这表示/00
或/
之前是00
。
演示:
public class Main {
public static void main(String[] args) {
String[] arr = { "01/00/00/00/00/00/00/", "01/02/03/00/00/00/00/", "10/25/03/56/00/00/00/" };
for (String s : arr) {
System.out.println(s + " => " + s.replaceAll("/00|(?<=(00))/", ""));
}
}
}
输出:
01/00/00/00/00/00/00/ => 01
01/02/03/00/00/00/00/ => 01/02/03
10/25/03/56/00/00/00/ => 10/25/03/56
注意:?<=
用于指定positive lookbehind。
答案 1 :(得分:0)
替代:
Pattern.compile("/00|/$", Pattern.MULTILINE).matcher(input).replaceAll("");
注意:当使用标志Pattern.MULTILINE时,将考虑边界匹配器'$'。
正则表达式显示在测试台和上下文中
public static void main(String[] args) {
String input = "01/00/00/00/00/00/00/\n"
+ "01/02/03/00/00/00/00/\n"
+ "10/25/03/56/00/00/00/";
String result = Pattern.compile("/00|/$", Pattern.MULTILINE).matcher(input).replaceAll("");
System.out.println(result);
}
输出:
01
01/02/03
10/25/03/56
答案 2 :(得分:0)
无需先行或后行。只需查找一个斜杠,后面跟随任意数量的00/
序列:
str = str.replaceFirst("/(00/)*$", "");
为获得更好的性能,您可以将群组设为非捕获群组:
str = str.replaceFirst("/(?:00/)*$", "");