2013-12-18 37 views
0

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

例如: 输入:B3,范围:B1:B10 - 真
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; 
} 
} 
+0

这段代码有什么问题? ''A1:B2“,”B1“'应该发生什么? –

回答

1

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

使用(\\d+)而不是(\\d)+这样m.group(i)是整个数字串。

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

你打算find()还是应该匹配整个字符串:matches()

+0

我需要匹配(),因为我想匹配整个字符串。 \\ D +如何获得我需要的字母前缀? – Praveen

+0

'\\ D'是非数字的正则表达式,因为数字是'\\ d'。请参阅[模式](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)。 –

0

由于乔普埃根

我更改如下我正则表达式,

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

现在,它的工作原理与上面的代码。