java正则表达式逗号分隔数字

时间:2016-11-17 16:49:33

标签: java regex

我试图从消息的有效负载中获取1个long(时间戳)和3个浮点数,我传递的字符串看起来像这样(忽略引号):

"5737540811294,359.306580,7.948747,6.6707006621"

使用此方法

private static void processAnglesMsg(String s) {
   final Pattern dataTFFFsplit = Pattern.compile( "[+-]([0-9]+),"
                                                + "[+-]([0-9]*[.])?[0-9]+,"
                                                + "[+-]([0-9]*[.])?[0-9]+,"
                                                + "[+-]([0-9]*[.])?[0-9]+,");
    Matcher data = dataTFFFsplit.matcher(s.trim());
    if(data.matches()) {
        Long time = Long.parseLong(data.group(1));
        float yaw = Float.parseFloat(data.group(2));
        float pitch = Float.parseFloat(data.group(3));
        float roll = Float.parseFloat(data.group(4));
        System.out.format("Angles - [%8d] Yaw: %08.3f Pitch: %08.3f Roll: %08.3f%n",time,yaw, pitch,roll);
    } else {
        if(debugLevel>=4) System.out.println("DEBUG processAnglesMsg: "+s);
    }
}

我继续使用以下命令获取调试代码:

  

DEBUG processAnglesMsg:5737540811294,359.306580,7.948747,6.6707006621 *

所以看起来我的模式不起作用而data.matches()返回false,尽管经常搜索我看不出我做错了什么。我确实希望模式允许使用可选的+或 - 即使我当前的数据不包含这个。

2 个答案:

答案 0 :(得分:3)

您的子Pattern的问题在于+ / -符号不是可选的,在您的示例中不匹配(最后一个子模式也需要逗号) ,但你的例子并不以一个结束。

假设您的示例String将永远不会包含用于本地化数字分隔目的的逗号,并且您不想使用CSV解析框架:

String example = "5737540811294,359.306580,7.948747,6.6707006621";
// splits the input based on comma
String[] split = example.split(",");
// parses desired data types
// will throw runtime NumberFormatException if something's un-parseable
System.out.println(Long.parseLong(split[0]));
System.out.println(Float.parseFloat(split[1]));
System.out.println(Float.parseFloat(split[2]));
System.out.println(Float.parseFloat(split[3]));

输出(值四舍五入)

5737540811294
359.30658
7.948747
6.6707006

注意

如果您希望保留尽可能多的小数,也可以使用BigDecimal代替Float

例如:

System.out.println(new BigDecimal(split[3]));

<强>输出

6.6707006621

答案 1 :(得分:1)

使用扫描仪:

Scanner scanner = new Scanner(input).useDelimiter(",");
long time = scanner.nextLong();
float yaw = scanner.nextFloat();
float pitch = scanner.nextFloat();
float roll = scanner.nextFloat();

更容易编码,更易于阅读。

如果输入不总是匹配:

Scanner scanner = new Scanner(input).useDelimiter(",");
try {
    long time = scanner.nextLong();
    float yaw = scanner.nextFloat();
    float pitch = scanner.nextFloat();
    float roll = scanner.nextFloat();
    System.out.format("Angles - [%8d] Yaw: %08.3f Pitch: %08.3f Roll: %08.3f%n",time,yaw, pitch,roll);
} catch (NoSuchElementException e) {
    // input didn't match due to insufficient elements or parsing failure
}