Nox Nox - 6 months ago 10
Java Question

Parse signed number from string

I have string like:


I don't want to parse using Pattern and Matcher. I have code:

string.replaceAll("regex", ""));

How to make
to exclude all symbols except a "-" to get string like:



You can use this negative lookahead regex:

String s = "-------5548481818fgh7hf8ghf----fgh54f4578";

String r = s.replaceAll("(?!^[-+])\\D+", "");
//=> -554848181878544578

(?!^-)\D will replace each non-digit except the hyphen at start.

RegEx Demo