Use variables in pattern matcher

ⅰ亾dé卋堺 提交于 2019-12-12 09:36:22

问题


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


回答1:


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()) {


来源:https://stackoverflow.com/questions/10317603/use-variables-in-pattern-matcher

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!