[英]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. 0
's only. 0
的连续链。 \\b
, there is no way it can be formed for 10000
because the word boundary \\b
is before 1
and not 0
\\b
开头,因此无法形成10000
因为单词边界\\b
在1
之前而不是0
(?=\\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 . 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)", " ")
EDIT: Updating as per @SebastianProske's suggestions. 编辑:根据@SebastianProske的建议进行更新。 Thanks!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.