【问题标题】:I need a regex that matches numbers depending on a variable我需要一个根据变量匹配数字的正则表达式
【发布时间】:2016-05-27 21:50:45
【问题描述】:

我在尝试为我的代码查找正则表达式时遇到了一些问题。这里是:

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,等等...

Board size 只能是 1 到 9。

我写过这段话是为了在输入失败的情况下要求另一个数字。

【问题讨论】:

  • 你为什么使用字符串工具,正则表达式,因为听起来最好通过简单的数字布尔检查来处理?看起来您正在尝试使用螺丝刀来锯断木板 - 您使用了错误的工具来完成这项工作。
  • 我猜Zawinski 在他写道:“有些人遇到问题时,会想‘我知道,我会使用正则表达式。’”现在他们有两个问题。”

标签: java regex match


【解决方案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
} 

【讨论】:

  • 甚至不需要parseInt,因为Scanner 有一个nextInt() 方法。
  • 山姆是真的。我只是提供了一个非常通用的示例(即在这种情况下input 可以是任何字符串输入)。
  • 谢谢,你真的帮了我。一个条件比做一个模式更简单..当你写几个小时时就会发生这种情况哈哈
猜你喜欢
  • 2018-01-07
  • 2010-09-23
  • 2011-09-22
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 2015-07-06
相关资源
最近更新 更多