从字符串中解析带符号的数字
Parse signed number from string
我有这样的字符串:
"-------5548481818fgh7hf8ghf----fgh54f4578"
我不想使用模式和匹配器进行解析。我有代码:
string.replaceAll("regex", ""));
如何使 regex
排除除“-”之外的所有符号以获得如下字符串:
-554848181878544578
这会起作用
String Str = new String("-------5548481818fgh7hf8ghf----fgh54f4578-");
String tmp = Str.replaceAll("([-+])+|([^\d])","").replaceAll("\d[+-](\d|$)","");
System.out.println(tmp);
您可以使用这个否定的先行正则表达式:
String s = "-------5548481818fgh7hf8ghf----fgh54f4578";
String r = s.replaceAll("(?!^[-+])\D+", "");
//=> -554848181878544578
(?!^-)\D
将替换除开头连字符之外的每个非数字。
备选方案:抓住相反的方向,而不是替换负面的。您选择删除不需要的字符,而不是抓取您 do 想要的字符,这似乎是武断的。 javascript 中的示例:
s = "-------5548481818fgh7hf8ghf----fgh54f4578"
s = '-' + s.match(/[0-9]+/g).join('')
// "-554848181878544578"
我有这样的字符串:
"-------5548481818fgh7hf8ghf----fgh54f4578"
我不想使用模式和匹配器进行解析。我有代码:
string.replaceAll("regex", ""));
如何使 regex
排除除“-”之外的所有符号以获得如下字符串:
-554848181878544578
这会起作用
String Str = new String("-------5548481818fgh7hf8ghf----fgh54f4578-");
String tmp = Str.replaceAll("([-+])+|([^\d])","").replaceAll("\d[+-](\d|$)","");
System.out.println(tmp);
您可以使用这个否定的先行正则表达式:
String s = "-------5548481818fgh7hf8ghf----fgh54f4578";
String r = s.replaceAll("(?!^[-+])\D+", "");
//=> -554848181878544578
(?!^-)\D
将替换除开头连字符之外的每个非数字。
备选方案:抓住相反的方向,而不是替换负面的。您选择删除不需要的字符,而不是抓取您 do 想要的字符,这似乎是武断的。 javascript 中的示例:
s = "-------5548481818fgh7hf8ghf----fgh54f4578"
s = '-' + s.match(/[0-9]+/g).join('')
// "-554848181878544578"