2010-10-18 113 views
1

這個regex是否有一個或兩個組?

我試圖使用第二組訪問bookTitle但得到的錯誤:

Pattern pattern = Pattern.compile("^\\s*(.*?)\\s+-\\s+'(.*)'\\s*$"); 
Matcher matcher = pattern.matcher("William Faulkner - 'Light In August'"); 
String author = matcher.group(1).trim(); 
String bookTitle = matcher.group(2).trim(); 

回答

3

有兩個組,但這個錯誤是因爲什麼都沒有做與匹配器。
嘗試獲取第一組matcher.group(1)時,拋出IllegalStateException。
必須調用matches,lookingAtfind的方法之一。
這應該做到:

Pattern pattern = Pattern.compile("^\\s*(.*?)\\s+-\\s+'(.*)'\\s*$"); 
Matcher matcher = pattern.matcher("William Faulkner - 'Light In August'"); 
if (matcher.matches()) { 
    String author = matcher.group(1).trim(); 
    String bookTitle = matcher.group(2).trim(); 
    ... 
} else { 
    // not matched, what now? 
} 
4

兩組 - '是不是在正則表達式特殊字符。你得到的錯誤是什麼?

另外,他們不是零爲基礎。來自javadoc:

Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group().

+1

剛剛在我的電腦上測試了你的正則表達式,它適用於我 – 2010-10-18 20:59:12

2

在您提問之前添加以下內容之一。

matcher.find(); 
matcher.maches(); 

這是如何工作:

A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations:

The matches method attempts to match the entire input sequence against the pattern.

The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.

The find method scans the input sequence looking for the next subsequence that matches the pattern.

來源:Java Api

我個人建議你先刪除多個空格,然後分裂和修剪 - 中提琴簡單,測試和工程。

試試這個:

String s = "William   Faulkner - 'Light In August'"; 
    String o[] = s.replaceAll("\\s+", " ").split("-"); 
    String author = o[0].trim(); 
    String bookTitle = o[1].trim(); 

,如果您:

System.out.println(author); 
    System.out.println(bookTitle); 

然後輸出爲:

William Faulkner 
'Light In August' 
1

的問題是Matcher類好像是懶惰:它實際上推遲評估,直到()方法被調用的比賽。試試這個

Pattern pattern = Pattern.compile("^\\s*(.*)\\s+-\\s+'(.*)'\\s*$"); 
Matcher matcher = pattern.matcher("William Faulkner - 'Light In August'"); 

if (matcher.matches()) { 
    String author = matcher.group(1).trim(); 
    String bookTitle = matcher.group(2).trim(); 

    System.out.println(author + "/" + bookTitle); 
} 
else { 
    System.out.println("No match!"); 
} 

你也可能要改變組(+),以確保你不會用空作者/標題買書。

相關問題