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

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

问题描述

我已经看到有关如何在 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

推荐答案

Regex 是工作的最佳工具;它应该是什么取决于问题规范.以下删除前导零,但在必要时保留一个(即它不会只是将 "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
    • 重复lookaroundsanchors一个>
    • See also

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

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