2013-12-18 36 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+)"; 

現在,它的工作原理與上面的代碼。