I have the following:
JavaScript
x
if (mobile.matches("[0-9]{6,20}")) {
}
But would like to replace the {6,20} with variable values due to them been dynamic in some cases.
I.e.
JavaScript
int minValue = 11;
int maxValue = 20
if (mobile.matches("[0-9]{minValue,maxValue}")) {
}
How can I include variables in the Reg Exp?
Thanks
Advertisement
Answer
Use Java’s simple string concatenation, using the plus sign.
JavaScript
if (mobile.matches("[0-9]{" + minValue + "," + maxValue + "}")) {
Indeed, as Michael suggested compiling it is better for performance if you use it a lot.
JavaScript
Pattern pattern = Pattern.compile("[0-9]{" + minValue + "," + maxValue + "}");
Then use it when needed like this:
JavaScript
Matcher m = pattern.matcher(mobile);
if (m.matches()) {