我在尝试为代码找到正则表达式时遇到了一些问题。这是:
Scanner key = new Scanner(System.in);
//this is the variable
int s = 4;
String input = "";
String bregex = "[1-9][0-9]{1," + (s*s) + "}";
boolean cfgmatch = false;
while(cfgmatch == false){
input = key.next();
Pattern cfgbp = Pattern.compile(bregex);
Matcher bm = cfgbp.matcher(input);
if(bm.matches()){
System.out.println("working");
}
else{
System.out.println("not working");
}
}
我正在尝试制作一个正则表达式来重新制作一块电路板中的多个单元格。单元格数不能高于单元格的空间,即“s * s”。
示例:如果电路板尺寸为4,则输入可以是1到16,如果是5,则从1到25,等等......
电路板尺寸只能是1到9。
我已经写过,在输入失败的情况下要求另一个号码。
答案 0 :(得分:1)
注意正则表达式
虽然正则表达式可能对此有用,但它实际上更适合处理模式匹配而不是算术运算。您当前的正则表达式将生成s*s
个数字,这不会定义您要查找的范围:
// If s = 4, then this regular express will match any string that begins with a 1 and
// would allow any values from 1-99999999999999999 as opposed to the 1-16 you are expecting
String bregex = "[1-9][0-9]{1,16}";
考虑更简单的方法
如果您要将数字输入与其他值进行比较(即此数字小于x),您可能最好避免使用它:
// Is your number less than the largest possible square value?
if(parseInt(input) <= s*s){
// Valid
}
else {
// Invalid
}