Java 在模式匹配器中使用变量

Java 在模式匹配器中使用变量,java,regex,matcher,Java,Regex,Matcher,我有以下资料: if (mobile.matches("[0-9]{6,20}")) { ... } 但是想用变量值替换{6,20},因为它们在某些情况下是动态的 即 如何在Reg Exp中包含变量 感谢使用Java的简单字符串连接,使用加号 if (mobile.matches("[0-9]{" + minValue + "," + maxValue + "}")) { 事实上,正如Michael所建议的那样,如果您经常使用它,编译它对性能更有利 Pattern pattern =

我有以下资料:

if (mobile.matches("[0-9]{6,20}")) {
   ...
}
但是想用变量值替换{6,20},因为它们在某些情况下是动态的

如何在Reg Exp中包含变量


感谢使用Java的简单字符串连接,使用加号

if (mobile.matches("[0-9]{" + minValue + "," + maxValue + "}")) {
事实上,正如Michael所建议的那样,如果您经常使用它,编译它对性能更有利

Pattern pattern = Pattern.compile("[0-9]{" + minValue + "," + maxValue + "}");
然后在需要时使用它,如下所示:

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

您还可以使用
String.format(“[0-9]{%s,%s}”,minValue,maxValue)

如果您要经常使用正则表达式匹配器,并且这些值不会更改,那么您可以预编译它。这样做很有效,我只是想可能还有其他推荐的方法。为马蒂恩和安迪干杯。
Matcher m = pattern.matcher(mobile);
if (m.matches()) {