从字符串的数字部分删除所有前导零

时间:2017-02-21 07:19:59

标签: java string replace

我试图从字符串的数字部分删除所有前导零。我想出了这个代码(下面)。从给定的例子可以看出它。但是当我在开头添加一个'0'时它不会给出正确的输出。有人知道如何实现这个目标吗?提前致谢

输入:(2016)abc00701def00019z - >输出:(2016)abc701def19z - > resut:正确

输入:0(2016)abc00701def00019z - >输出:(2016)abc71def19z - >结果:错误 - >预期产出:(2016)abc701def19z

编辑:该字符串可以包含非英文字母。

String localReference = "(2016)abc00701def00019z";
String localReference1 = localReference.replaceAll("[^0-9]+", " ");
List<String> lists =  Arrays.asList(localReference1.trim().split(" "));
System.out.println(lists.toString());
String[] replacedString = new String[5];
String[] searchedString = new String[5];
int counter = 0;
for (String list : lists) {
   String s = CharMatcher.is('0').trimLeadingFrom(list);
   replacedString[counter] = s;
   searchedString[counter++] = list;

   System.out.println(String.format("Search: %s, replace: %s", list,s));
}
System.out.println(StringUtils.replaceEach(localReference, searchedString, replacedString));

3 个答案:

答案 0 :(得分:3)

str.replaceAll("(^|[^0-9])0+", "$1");

这将删除非数字字符后面和字符串开头的任何零行。

答案 1 :(得分:0)

java有\ P {Alpha} +,它匹配任何非字母字符,然后删除起始零点。

String stringToSearch = "0(2016)abc00701def00019z"; 
Pattern p1 = Pattern.compile("\\P{Alpha}+");
Matcher m = p1.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()){
    m.appendReplacement(sb,m.group().replaceAll("\\b0+",""));
}
m.appendTail(sb);
System.out.println(sb.toString());

output:

(2016)abc701def19z

答案 2 :(得分:0)

我尝试使用Regex完成任务,并且能够根据您提供的两个测试用例执行所需的操作。下面代码中的$ 1和$ 2也是前面Regex中()括号中的部分。

请找到以下代码:

    public class Demo {

        public static void main(String[] args) {

            String str = "0(2016)abc00701def00019z";

/*Below line replaces all 0's which come after any a-z or A-Z and which have any number after them from 1-9. */
            str = str.replaceAll("([a-zA-Z]+)0+([1-9]+)", "$1$2");
            //Below line only replace the 0's coming in the start of the string
            str = str.replaceAll("^0+","");
            System.out.println(str);
        }
    }