Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following:

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.

int minValue = 11;
int maxValue = 20

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

How can I include variables in the Reg Exp?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
347 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use Java's simple string concatenation, using the plus sign.

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

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

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

Then use it when needed like this:

Matcher m = pattern.matcher(mobile);
if (m.matches()) {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...