2012-06-04 24 views
0

我試圖使用掃描儀從以下形式的字符串中的代碼行來讀取解析代碼值「p.addPoint(X,Y);」掃描儀 - 使用正則表達式定界符

正則表達式格式我後:

*anything*.addPoint(*spaces or nothing* OR ,*spaces or nothing*

什麼我試過到目前爲止不工作:[[.]+\\.addPoint(&&[\\s]*[,[\\s]*]]

任何想法我做錯了嗎?

+1

'[...]'定義了一個字符類,而你至今什麼是完全破碎。研究括號在正則表達式中的含義並重試。 –

+0

我對_spaces或nothing_感到困惑。只有空格,沒有別的?你不想捕捉數值嗎? – Litty

+0

這是分隔符正則表達式,基本上是作爲整數之間的分隔符傳遞的。 –

回答

2

我在Python測試這一點,但正則表達式應該轉移到Java:

>>> regex = '(\w+\.addPoint\(\s*|\s*,\s*|\s*\)\s*)' 
>>> re.split(regex, 'poly.addPoint(3, 7)') 
['', 'poly.addPoint(', '3', ', ', '7', ')', ''] 

你的正則表達式似乎嚴重畸形。即使不匹配,在字符串開頭匹配無限次重複的.通配符可能會導致大量的文本匹配,這些匹配實際上並不相關/需要。

編輯:誤解了原來的規格,目前正則表達式應該是正確的。

+0

似乎並不奏效...... 我的輸入爲「poly.addPoint(3, 7); //#5「注意,它應該同時接收3和7 –

+0

你得到了什麼輸出,你需要什麼輸出?更具體地說,你是否試圖在匹配嗎?你們是不是要組的數值參數,並提取它們?更多詳情,請。 –

+0

使用正則表達式作爲分隔符掃描儀,我想用一段時間(hasNextInt()),並抓住兩個3和7使用nextInt整數();兩次這樣說你 我沒有收到來自您的正則表達式的任何輸出 –

0

另一種方式:

public class MyPattern { 

    private static final Pattern ADD_POINT; 
    static { 
     String varName = "[\\p{Alnum}_]++"; 
     String argVal = "([\\p{Alnum}_\\p{Space}]++)"; 
     String regex = "(" + varName + ")\\.addPoint\\(" + 
       argVal + "," + 
       argVal + "\\);"; 
     ADD_POINT = Pattern.compile(regex); 
     System.out.println("The Pattern is: " + ADD_POINT.pattern()); 
    } 

    public void findIt(String filename) throws FileNotFoundException { 
     Scanner s = new Scanner(new FileReader(filename)); 

     while (s.findWithinHorizon(ADD_POINT, 0) != null) { 
      final MatchResult m = s.match(); 
      System.out.println(m.group(0)); 
      System.out.println(" arg1=" + m.group(2).trim()); 
      System.out.println(" arg2=" + m.group(3).trim()); 
     } 
    } 

    public static void main(String[] args) throws FileNotFoundException { 
     MyPattern p = new MyPattern(); 
     final String fname = "addPoint.txt"; 
     p.findIt(fname); 
    } 

}