【问题标题】:Alphanumeric range checker - whether B3 is in B1:B10字母数字范围检查器 - B3 是否在 B1:B10 中
【发布时间】:2013-12-18 12:25:38
【问题描述】:

如何在java中编写一个字母数字范围检查器,它将检查给定的字母数字值是否在范围内。

例如: 输入:B3,范围:B1:B10 - true
B1, B1:B10 - 真
B10, B1:B10 - 真
B1, B3:B10 - 假

我的尝试失败了超过 1 位数字,例如在 B3:B10 中,第二个前缀应该是 'B' 并且 num 应该是 10,但我得到 B1 和 0。正则表达式有什么问题吗?

public class Main {

public static final String RANGE_PATTERN = "(.+)(\\d)+:(.+)(\\d)+";
public static final String INPUT_PATTERN = "(.+)(\\d)+";
public static final Pattern P1 = Pattern.compile(RANGE_PATTERN);
public static final Pattern P2 = Pattern.compile(INPUT_PATTERN);

public static void main(String[] args) {
    System.out.println(checkWithInRange("B3:B10", "B7"));
}

public static boolean checkWithInRange(String range, String input) {
    Matcher m1 = P1.matcher(range);
    Matcher m2 = P2.matcher(input);
    if (m1.find() && m2.find()) {
        String prefix1 = m1.group(1);
        String num1 = m1.group(2);
        String prefix2 = m1.group(3);
        String num2 = m1.group(4);

        String inputPrefix = m2.group(1);
        String inputNum = m2.group(2);

        if (prefix1.equalsIgnoreCase(prefix2) && prefix2.equalsIgnoreCase(inputPrefix)) {
            int n1 = Integer.parseInt(num1);
            int n2 = Integer.parseInt(num2);
            int n3 = Integer.parseInt(inputNum);
            if (n3 >= n1 && n3 <= n2) {
                return true;
            }
        }
    }
    return false;
}
}

【问题讨论】:

  • 这段代码有什么问题? "A1:B2", "B1" 会发生什么?

标签: java regex alphanumeric


【解决方案1】:

使用"(.+?)... 接收最短序列(无数字)。或者更好"(\\D+)...。

使用(\\d+) 代替(\\d)+,这样m.group(i) 就是整个数字字符串。

不需要对组使用空检查,也许您打算使用可选前缀:(\\D*)。

您是打算使用find() 还是应该匹配整个字符串:matches()?

【讨论】:

  • 我需要matches() 因为我想匹配整个字符串。 \\D+ 将如何获得我需要的 alpha 前缀?
  • \\D 是非数字的正则表达式,因为数字是\\d。见Pattern。
【解决方案2】:

感谢乔普·埃根

我改变了我的正则表达式如下,

public static final String RANGE_PATTERN = "(\\D+)(\\d+):(\\D+)(\\d+)";
public static final String INPUT_PATTERN = "(\\D+)(\\d+)";

现在可以使用上面的代码了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    相关资源
    最近更新 更多