Replace everything except positive/negative numbers
Asked Answered
W

2

4

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.

Whited answered 6/9, 2015 at 9:14 Comment(0)
M
2

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

Magi answered 6/9, 2015 at 9:16 Comment(3)
what is the use of equals sign?Whited
0 | success. id - 1234| is returning 01234 and not 0 1234 in your replaceall regexWhited
Hmm this demo shows a space between 0 and 1234 but replace is not recommended, better to use matching.Magi
D
0

I used this in Kotlin to replace all non-Double characters before parsing to a Double:

val double = str.replace("[^0-9.-]".toRegex(), "").toDoubleOrNull()
Dysarthria answered 17/12, 2020 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.