Pankaj Singhal
Pankaj Singhal

Reputation: 16053

Replace everything except positive/negative numbers

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

Answers (2)

jc12
jc12

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

anubhava
anubhava

Reputation: 785068

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

Upvotes: 2

Related Questions