简体   繁体   English

替换前导零

[英]Replace Leading Zeros

Given a String containing this: 给定一个包含以下内容的字符串:

Count     %
===========
00000  000%
00012  001%
00905  099%

I want it to look like this: 我希望它看起来像这样:

Count     %
===========
    0    0%
   12    1%
  905   99%

The closest I could get is this: 我能得到的最接近的是:

Count     %
===========
    %
 12   1%
 905   99%

Using this code: 使用此代码:

strv.replaceAll("\\b0+", " ")

Since you want the space to be maintained as-is, it is important that each 0 is matched individually and then replaced with a space: ' 由于您希望空间保持原样,因此将每个0匹配,然后替换为空格非常重要: '. '。 Take a look at this regex: 看一下这个正则表达式:

(?<=\b|\G)0(?=\d)
  • (?<=\\b|\\G) is a positive lookbehind which ensures that the matching 0 is preceeded by either \\b or \\G (?<=\\b|\\G)是正向后移,可确保匹配的0\\b\\G开头
    • \\b represents a word boundary which means \\b0 will help match the first zero \\b表示单词边界,这意味着\\b0将帮助匹配第一个零
    • \\G helps assert the position at the end of the previous match (which will be after the previous zero). \\G帮助在上一个比赛的末尾(将在前一个零之后)断言位置。 So it will help match the next zero and so on. 因此,它将有助于匹配下一个零,依此类推。 Thus forming a continuous chain of 0 's only. 因此仅形成0的连续链。
    • Note that since the chain starts with \\b , there is no way it can be formed for 10000 because the word boundary \\b is before 1 and not 0 请注意,由于该链以\\b开头,因此无法形成10000因为单词边界\\b1之前而不是0
  • Finally a positive lookahead (?=\\d) also needs to be added because if an input contains only zero's then we need to leave one zero behind. 最后,还需要添加正向超前(?=\\d) ,因为如果输入仅包含零,那么我们需要在后面保留一个零。 This positive lookahead tells the engine to match all zeros which are followed by a number . 该正向提前指示引擎使所有零与后跟一个数字匹配 So, if input is 0000 , then regex will match first 3 0 's because last one isn't followed by a digit . 因此,如果输入为0000 ,则正则表达式将匹配前3个0 ,因为后一个不跟数字

Usage 用法

strv.replaceAll("(?<=\\b|\\G)0(?=\\d)", " ")

Regex101 Demo Regex101演示

EDIT: Updating as per @SebastianProske's suggestions. 编辑:根据@SebastianProske的建议进行更新。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM