2012-12-06 16 views
0

組我將如何解析兩個數字在下面的字符串:檢索捕獲從正則表達式匹配器

String fName = "Run_1_vs_2_pw_optimal_mapping.txt"; 

我試了一下這樣的,但它不工作:

Pattern filePatt = Pattern.compile("Run_(\\d+)_vs_(\\d+)_", Pattern.CASE_INSENSITIVE); 

    Matcher scanner = this.filePatt.matcher(fName); 
    while (scanner.find()) { 
      int groupSize = scanner.groupCount(); 
      if (groupSize == 2) { 
       firstRun = Integer.parseInt(scanner.group(0)); 
       secondRun = Integer.parseInt(scanner.group(1)); 
      } 
      break; 
    } 

然而,這不起作用,因爲scanner.group(0)返回Run_1_vs_2。但爲什麼?

回答

2

請參閱the documentation

捕獲組從左到右索引,從1開始。組0表示整個模式,因此表達式m.group(0)等同於m.group()。

使用group(1)group(2)

+0

非常感謝你,你們倆! – CodingButStillAlive

2

因爲組號碼0對應完整匹配。捕獲從1計數。你想要的是捕獲1(第一組圓括號)和2(第二組圓括號)。

+0

非常感謝你們,你們倆! – CodingButStillAlive

+0

@ user1881788請考慮接受我們的一個答案(最好是另一個答案!),給答案者一些信用,並向未來的訪問者展示你的問題已經解決(以及如何)。 –