我有像
1) "CAP07560"
2) "CAP41060"
3) "CAP43500"
4) "CAP22390"
Run Code Online (Sandbox Code Playgroud)
我想"CAP"先从字符串中删除文本,然后再为剩余的字符串删除最后的“ 0”,并在字符串的开头删除所有零。
所以我的输出将是:
1) "756"
2) "4106"
3) "4350"
4) "2239"
Run Code Online (Sandbox Code Playgroud)
我尝试了以下-
public class RegexTest {
public static void main(String[] args) {
// drop the last "0" and then drop any
// zeros at the start of the remaining number.
String str = "CAP07560";
String pattern = "^CAP[ 0]*|( |(?<!\\d))*$";
str = str.replaceAll(pattern, "");
System.out.println(str);
}
}
Run Code Online (Sandbox Code Playgroud)
我的输出: 7560
所以我的输出是,7560但应该是756。
您可以使用交替在单个replaceAll调用中执行此操作:
str = str.replacAll("^CAP0*|0$", "");
Run Code Online (Sandbox Code Playgroud)
正则表达式详细信息:
^CAP0*:匹配开始时CAP跟着0或多个零|: 要么0$:匹配最后一个零