Nox Nox - 2 years ago 139
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:


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download