2010-10-18 111 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!"); 
} 

你也可能要改变组(+),以确保你不会用空作者/标题买书。

相关问题