本文介绍了在模式匹配器中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容:
if (mobile.matches("[0-9]{6,20}")) {
...
}
但是由于变量在某些情况下是动态的,因此想用变量值替换{6,20}.
But would like to replace the {6,20} with variable values due to them been dynamic in some cases.
即
int minValue = 11;
int maxValue = 20
if (mobile.matches("[0-9]{minValue,maxValue}")) {
...
}
如何在Reg Exp中包括变量?
How can I include variables in the Reg Exp?
谢谢
推荐答案
使用Java的简单字符串连接,并使用加号.
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()) {
这篇关于在模式匹配器中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!