Nox Nox - 7 months ago 27
Java Question

Parse signed number from string

I have string like:

"-------5548481818fgh7hf8ghf----fgh54f4578"


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

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


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

-554848181878544578

Answer

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

Comments