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.
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