正则表达式不是我的强项。假设我需要一个用于字符串的自定义解析器,该解析器会去除所有字母,多个小数点和字母的字符串。
例如,输入字符串为“--1-2.3-gf5.47”,解析器将返回
“-12.3547”。
我只能想出这样的变化:
string.replaceAll("[^(\\-?)(\\.?)(\\d+)]", "")
它删除了字母,但保留了其他所有内容。有指针吗?
更多示例:
输入:-34.le.78-90
输出:-34.7890
输入:df56hfp.78
输出:56.78
一些规则:
小数点。
最佳答案
刚刚在ideone上进行了测试,它似乎可以工作。这些注释应该足以解释代码。您可以将其复制/粘贴到Ideone.com中,并根据需要进行测试。
可能可以为它编写一个正则表达式模式,但是最好实现以下类似的更简单/可读性更好的方法。
您给出的三个示例可以打印出来:
--1-2.3-gf5.47 -> -12.3547
-34.le.78-90 -> -34.7890
df56hfp.78 -> 56.78
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(strip_and_parse("--1-2.3-gf5.47"));
System.out.println(strip_and_parse("-34.le.78-90"));
System.out.println(strip_and_parse("df56hfp.78"));
}
public static String strip_and_parse(String input)
{
//remove anything not a period or digit (including hyphens) for output string
String output = input.replaceAll("[^\\.\\d]", "");
//add a hyphen to the beginning of 'out' if the original string started with one
if (input.startsWith("-"))
{
output = "-" + output;
}
//if the string contains a decimal point, remove all but the first one by splitting
//the output string into two strings and removing all the decimal points from the
//second half
if (output.indexOf(".") != -1)
{
output = output.substring(0, output.indexOf(".") + 1)
+ output.substring(output.indexOf(".") + 1, output.length()).replaceAll("[^\\d]", "");
}
return output;
}
}
关于regex - 用于自定义解析的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31709312/