Use variables in the template

I have the following:

if (mobile.matches("[0-9]{6,20}")) { ... } 

But I would like to replace {6,20} with the values โ€‹โ€‹of the variables because of their dynamic in some cases.

those.

 int minValue = 11; int maxValue = 20 if (mobile.matches("[0-9]{minValue,maxValue}")) { ... } 

How to include variables in Exp Exp?

thanks

+8
java regex matcher
source share
1 answer

Use Java direct concatenation using the plus sign.

 if (mobile.matches("[0-9]{" + minValue + "," + maxValue + "}")) { 

Indeed, as Michael suggested, compiling is better for performance if you use it a lot.

 Pattern pattern = Pattern.compile("[0-9]{" + minValue + "," + maxValue + "}"); 

Then use it if necessary:

 Matcher m = pattern.matcher(mobile); if (m.matches()) { 
+13
source share

All Articles