【问题标题】:Remove all the leading zero from the number part of a string从字符串的数字部分删除所有前导零
【发布时间】:2017-07-10 16:47:58
【问题描述】:

我正在尝试从字符串的数字部分中删除所有前导零。我想出了这段代码(如下)。从给定的示例中,它起作用了。但是当我在开头添加一个“0”时,它不会给出正确的输出。有人知道如何实现这一目标吗?提前致谢

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

输入: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));

【问题讨论】:

  • 我敢打赌它有一个正则表达式,但你也可以取出所有数字并将它们转换为一个整数。这将删除所有前导零。然后,您只需用新值替换以前的值
  • @XtremeBaumer 但是对于太大而无法容纳 int 的大量序列,这将失败
  • @Sentry 不确定,但也许 BigInteger 也会删除前导零。我怀疑你会有一个包含数字的字符串来重载 bigInteger
  • How to remove leading zeros from alphanumeric text? 的可能重复项这有帮助吗???
  • @CKing 不是真的。它只删除第一个零,但不删除字符串中间的零。您必须进行 2 次替换,但正则表达式应该与 1 次替换一起使用

标签: java string replace


【解决方案1】:
str.replaceAll("(^|[^0-9])0+", "$1");

这将删除非数字字符之后和字符串开头的所有零行。

【讨论】:

    【解决方案2】:

    我尝试使用正则表达式完成任务,并且能够根据您提供的两个测试用例完成所需的任务。下面代码中的 $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);
            }
        }
    

    【讨论】:

    • 感谢您的回复。但如果字符串包含非英文字母,这将失败。
    • 你还有哪些元素??
    • 我也有汉字而不是英文
    【解决方案3】:

    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
    

    【讨论】:

    • 感谢您的回复。但如果字符串包含非英文字母,这将失败。
    猜你喜欢
    • 2011-04-09
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2021-02-06
    • 2014-04-12
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多