简体   繁体   English

正则表达式解析双精度

[英]Regular Expression Parse Double

I am new to regular expressions. 我是新来的正则表达式。 I want to search for NUMBER(19, 4) and the method should return the value(in this case 19,4 ). 我想搜索NUMBER(19, 4) 19,4 ),该方法应返回值(在本例中为19,4 )。 But I always get 0 as result ! 但是我总是得到0

       int length =0;
       length = patternLength(datatype,"^NUMBER\\((\\d+)\\,\\s*\\)$","NUMBER");

    private static double patternLengthD(String datatype, String patternString, String startsWith) {
        double length=0;
        if (datatype.startsWith(startsWith)) {
            Pattern patternA = Pattern.compile(patternString);
            Matcher matcherA = patternA.matcher(datatype);
                if (matcherA.find()) {
                    length = Double.parseDouble(matcherA.group(1)); 
            }
        }
        return length;
    }

You are missing the matching of digits after the comma. 您缺少逗号后的数字匹配。
You also don't need to escape the , . 你也不必逃避, Use this: 用这个:

"^NUMBER\\((\\d+),\\s*(\\d+)\\)$"

This will give you the first number in group(1) and the second number in group(2) . 这将为您提供group(1)的第一个数字和group(2)的第二个数字。

It is however fairly strict on spaces, so you can be more lenient and match on values like " NUMBER ( 19 , 4 ) " by using this: 但是,它对空格非常严格,因此您可以使用以下方法来宽大一些,并匹配" NUMBER ( 19 , 4 ) "这样的值:

"^\\s*NUMBER\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)\\s*$"

In that case you'll have to drop your startsWith and just use the regex directly. 在这种情况下,您将必须删除startsWith并直接使用正则表达式。 Also, you can remove the anchors ( ^$ ) if you change find() to matches() . 另外,如果将find()更改为matchs(),则可以删除锚点( ^$ matches()

Since NUMBER(19) is usually allowed too. 由于通常也允许NUMBER(19) You can make the second value optional: 您可以将第二个值设为可选:

"\\s*NUMBER\\s*\\(\\s*(\\d+)\\s*(?:,\\s*(\\d+)\\s*)?\\)\\s*"

group(2) will then return null if the second number is not given. 如果未提供第二个数字,则group(2)将返回null

See regex101 for demo . 有关演示,请参见regex101


Note that your code doesn't compile. 请注意,您的代码无法编译。
Your method returns a double , but length is an int . 您的方法返回一个double ,但是length是一个int

Although 19,4 looks like a floating point number, it is not, and representing it as such is wrong. 尽管19,4看起来像一个浮点数,但实际上不是,并且如此表示是错误的。
You should store the two values separately. 您应该分别存储两个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM