Reputation: 317
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
). But I always get 0
as result !
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;
}
Upvotes: 0
Views: 132
Reputation: 159260
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)
.
It is however fairly strict on spaces, so you can be more lenient and match on values like " NUMBER ( 19 , 4 ) "
by using this:
"^\\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. Also, you can remove the anchors (^$
) if you change find()
to matches()
.
Since NUMBER(19)
is usually allowed too. 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.
See regex101 for demo.
Note that your code doesn't compile.
Your method returns a double
, but length
is an int
.
Although 19,4
looks like a floating point number, it is not, and representing it as such is wrong.
You should store the two values separately.
Upvotes: 2