需要使用正则表达式删除字符串中十进制数的尾随0 [复制]

时间:2022-11-03 16:58:09

This question already has an answer here:

这个问题在这里已有答案:

This is my regex:

这是我的正则表达式:

((((?<=(\d\.)(([1-9]))))|((?<=\d)\.[0])))((0)+) 

This is my Description:

这是我的描述:

af 0.044 00.22 44.3500,44.334000,0.5000,1.750,1.9000,0.1480,10.2500,0.7480",19.00 MM,62.00MM,12MM,12.0000MM,DRILL BIT,0.040',1.00 IN MINI BEND RADIUS|0.3120IN TIP DIA|36.00 IN LG,45MM,45.0000MM,30MM,30.0000MM,40MM,40.0000MM,40.00 15.20,40.00,15.20000:14.00,40.00;15.20000*14.00X40.00/15.20000(14.00),40.00\15.20000{14.00},40.00|15.20000[14.00],40.00?15.20000%14.00,15.20000{14.00},40.00|15.20000,15.20000%14.00, 345.00 354.34500aa 354.aa 354. ABC.000 17.0

As per requirement it should removing trailing 0's from the description.The above regex is removing the zeros but failing in some conditions. Like its failing on if value is 0.040, can anyone suggest me a better regex which would satisfy all the conditions.

根据要求,它应该从描述中删除尾随0。上面的正则表达式删除零但在某些条件下失败。就像它的失败,如果值是0.040,任何人都可以建议我一个更好的正则表达式,它将满足所有条件。

2 个解决方案

#1


1  

s = s.replaceAll("(\\d\\.\\d*[1-9])0+\\b", "$1")
     .replaceAll("(\\d)\\.0+\\b", "$1");

For the two cases 1.034000 to 1.034 and 1.000

对于两种情况1.034000到1.034和1.000

#2


1  

Based on the expected results of your comments you just want to remove the .0 from decimals that end with them. In that case this should work:

根据您的评论的预期结果,您只想从以它们结尾的小数中删除.0。在这种情况下,这应该工作:

s = s.replaceAll("([0-9])+[.][0](?![0-9])", "$1");

Hence : 123.0 becomes 123

因此:123.0变为123

To do a bit more thourough 0-cleaning. A bit of lazy matching and a negative lookahead could do the job.

通过0清洁做多一点。一些懒惰的匹配和负面的前瞻可以完成这项工作。

0*([0-9]+[.][0-9][0-9]*?)0+(?![0-9])

For this test example:

对于此测试示例:

String s = "0.010 00.20200,003.30330;10044.04400M,5.0";
s = s.replaceAll("0*([0-9]+[.][0-9][0-9]*?)0+(?![0-9])", "$1");

s will return:

将返回:

0.01 0.202,3.3033;10044.044M,5.0

#1


1  

s = s.replaceAll("(\\d\\.\\d*[1-9])0+\\b", "$1")
     .replaceAll("(\\d)\\.0+\\b", "$1");

For the two cases 1.034000 to 1.034 and 1.000

对于两种情况1.034000到1.034和1.000

#2


1  

Based on the expected results of your comments you just want to remove the .0 from decimals that end with them. In that case this should work:

根据您的评论的预期结果,您只想从以它们结尾的小数中删除.0。在这种情况下,这应该工作:

s = s.replaceAll("([0-9])+[.][0](?![0-9])", "$1");

Hence : 123.0 becomes 123

因此:123.0变为123

To do a bit more thourough 0-cleaning. A bit of lazy matching and a negative lookahead could do the job.

通过0清洁做多一点。一些懒惰的匹配和负面的前瞻可以完成这项工作。

0*([0-9]+[.][0-9][0-9]*?)0+(?![0-9])

For this test example:

对于此测试示例:

String s = "0.010 00.20200,003.30330;10044.04400M,5.0";
s = s.replaceAll("0*([0-9]+[.][0-9][0-9]*?)0+(?![0-9])", "$1");

s will return:

将返回:

0.01 0.202,3.3033;10044.044M,5.0