2013-01-20 40 views
-3

我是Java編程語言的初學者。使用RegEx從座標中提取數字

當我輸入(1,2)到控制檯(包含括號)時,如何編寫代碼以使用RegEx提取第一個和第二個數字?

如果沒有這樣的表達式來提取括號內的第一個/第二個數字,我將不得不改變座標輸入到x,y而不用括號的方式,並且這應該更容易將數字提取出來用過的。

+0

座標始終是整數嗎? – arshajii

+0

是的,座標將始終爲整數。 – hlx98007

+0

我試過^ \(((\ d)+),但是這包括括號,我是RegEx的新手 – hlx98007

回答

1

試試這個代碼:

public static void main(String[] args) { 
    String searchString = "(7,32)"; 
    Pattern compile1 = Pattern.compile("\\(\\d+,"); 
    Pattern compile2 = Pattern.compile(",\\d+\\)"); 
    Matcher matcher1 = compile1.matcher(searchString); 
    Matcher matcher2 = compile2.matcher(searchString); 
    while (matcher1.find() && matcher2.find()) { 
     String group1 = matcher1.group(); 
     String group2 = matcher2.group(); 
     System.out.println("value 1: " + group1.substring(1, group1.length() - 1) + " value 2: " + group2.substring(1, group2.length() - 1)); 
    } 
} 

不,我覺得正則表達式是最好用在這裏。如果你知道的輸入將是形式:(號碼,號碼),我會先幹掉括號:

stringWithoutBrackets = searchString.substring(1, searchString.length()-1) 

和比分裂

String[] coordiantes = stringWithoutBrackets.split(","); 

通過正則表達式API看着令牌化它你也可以做這樣的事情:???

public static void main(String[] args) { 
    String searchString = "(7,32)"; 
    Pattern compile1 = Pattern.compile("(?<=\\()\\d+(?=,)"); 
    Pattern compile2 = Pattern.compile("(?<=,)\\d+(?=\\))"); 
    Matcher matcher1 = compile1.matcher(searchString); 
    Matcher matcher2 = compile2.matcher(searchString); 
    while (matcher1.find() && matcher2.find()) { 
     String group1 = matcher1.group(); 
     String group2 = matcher2.group(); 
     System.out.println("value 1: " + group1 + " value 2: " + group2); 
    } 
} 

主要的變化是,我用(?< == \)),(=),(< =),(= \) ),搜索括號和逗號,但不是caputre t下襬。但是我真的認爲這對於這項任務來說是一個矯枉過正。

+0

謝謝,但這不是我想要的。是否沒有這樣的表達,允許我只提取括號內的第一個數字(或第二個數字)? – hlx98007

+0

我認爲問題在於你想要搜索對於(「(1,2)」)不是你想要得到的(這是「1」或「2」)。我認爲你不能一步做到這一點,但你可以分兩步。在上面的代碼中可能更好,首先用正則表達式提取「(數字,數字)」,然後它應該很容易得到每個數字的子字符串和拆分,就像我上面顯示的那樣,還是它不是你想要的? – Kamil

+0

I'我在我的回答中添加了第二個命題,那就是不使用子字符串和拆分,而是合併複製一些模式。如果您只想查找第一個或第二個數字,則只能使用其中一個編譯/匹配器。 – Kamil