Replace everything except positive/negative numbers

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

There are many questions already answered for replacing everything positive numbers. But, I couldn't find any answer which preserves both positive and negative numbers. I want to replace everything that isn't number(positive or negative). The output should be the following eg.

0 | success. id - 1234| -> 0 1234

and

-10 | failure. id - 2345| -> -10 2345

Apparently this answers for the positive part.

回答1:

You can use this regex to match positive/negative integers:

[+-]?\b\d+\b 

RegEx Demo

to match positive/negative numbers including decimals:

[+-]?\b\d+(?:\.\d+)?\b 

Please note that rather than using replace you would be better off using above regex in Pattern and Matcher APIs and just get your matched data.


In case you can only use replace then use:

str = str.replaceAll( "([+-]?\\b\\d+\\b)|\\S+[ \\t]*", "$1" ); 

Replace Demo



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!