从字符串中解析带符号的数字

时间:2016-04-20 16:03:03

标签: java regex parsing regular-language

我的字符串如下:

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

我不想使用Pattern和Matcher进行解析。我有代码:

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

如何让regex排除除" - "之外的所有符号得到像这样的字符串:

-554848181878544578

3 个答案:

答案 0 :(得分:1)

您可以使用此负前瞻性正则表达式:

CommandLineJobRunner

String s = "-------5548481818fgh7hf8ghf----fgh54f4578"; String r = s.replaceAll("(?!^[-+])\\D+", ""); //=> -554848181878544578 将替换除开头处的连字符之外的每个非数字。

RegEx Demo

答案 1 :(得分:0)

这将有效

String Str = new String("-------5548481818fgh7hf8ghf----fgh54f4578-");
String tmp = Str.replaceAll("([-+])+|([^\\d])","$1").replaceAll("\\d[+-](\\d|$)","");
System.out.println(tmp);

<强> Ideone Demo

答案 2 :(得分:0)

替代方案:抓住相反的方向,而不是取代负面。您似乎已经选择删除您不想要的字符,而不是抓住您想要的字符。 javascript中的示例:

s = "-------5548481818fgh7hf8ghf----fgh54f4578"
s = '-' + s.match(/[0-9]+/g).join('')
// "-554848181878544578"
相关问题