如何从字母数字文本中删除前导零? [英] How to remove leading zeros from alphanumeric text?

查看:186
本文介绍了如何从字母数字文本中删除前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了如何在SO中为零添加前缀的问题。但不是其他方式!

I've seen questions on how to prefix zeros here in SO. But not the other way!

你们可以建议我如何删除字母数字文本中的前导零?是否有任何内置API或我是否需要编写方法来修剪前导零?

Can you guys suggest me how to remove the leading zeros in alphanumeric text? Are there any built-in APIs or do I need to write a method to trim the leading zeros?

示例:

01234 converts to 1234
0001234a converts to 1234a
001234-a converts to 1234-a
101234 remains as 101234
2509398 remains as 2509398
123z remains as 123z
000002829839 converts to 2829839


推荐答案

正则表达式是这项工作的最佳工具;应该是什么取决于问题规范。以下删除前导零,但如果需要则留下一个(即它不会将0转换为空白字符串)。

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

s.replaceFirst("^0+(?!$)", "")

^ 锚点将确保 0 + 匹配是在输入的开头。 (?!$)否定前瞻确保不会匹配整个字符串。

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!$) negative lookahead ensures that not the entire string will be matched.

测试工具:

String[] in = {
    "01234",         // "[1234]"
    "0001234a",      // "[1234a]"
    "101234",        // "[101234]"
    "000002829839",  // "[2829839]"
    "0",             // "[0]"
    "0000000",       // "[0]"
    "0000009",       // "[9]"
    "000000z",       // "[z]"
    "000000.z",      // "[.z]"
};
for (String s : in) {
    System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}



参见




  • regular-expressions.info


    • 重复 lookarounds 主播

    • See also

      • regular-expressions.info
        • repetitions, lookarounds, and anchors
        • 这篇关于如何从字母数字文本中删除前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆