Reputation: 16053
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.
Upvotes: 4
Views: 2085
Reputation: 1829
I used this in Kotlin to replace all non-Double characters before parsing to a Double:
val double = str.replace("[^0-9.-]".toRegex(), "").toDoubleOrNull()
Upvotes: 0
Reputation: 785068
You can use this regex to match positive/negative integers:
[+-]?\b\d+\b
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" );
Upvotes: 2