2013-05-14 98 views
1

Rubular我是在试探我的正则表达式:Java的正则表达式不工作(但确实在Rubular)

(\d+).html 

测试字符串:

"/magnoliaAuthor/Services/services/07.html" 

正如我需要,我回到 “07”作为第一个比赛组。完善。 我需要这个表达式在Java环境,所以我写了这段代码:

import java.util.regex.*; 

class Main 
{ 
    public static void main (String[] args) 
    { 
    String jcrPath = "/magnoliaAuthor/Services/services/07.html"; 
    Pattern pattern = Pattern.compile("(\\d+).html"); 
    Matcher matcher = pattern.matcher(jcrPath); 
    System.out.println(matcher.group()); 
    } 
} 

至于解释here,我加了问题再\我的正则表达式。 可悲的是我,编译和运行代码时,我得到以下异常: java.lang.IllegalStateException:没有找到匹配

有谁知道为什么没有任何比赛吗?

+0

点也是一个特殊字符。尝试'“(\\ d +)\\。html”'。另外,你在整个字符串上匹配正则表达式,所以它应该是'“。*(\\ d +)\\。html”',其中'。+'开头是任意字符序列。 – Jacopofar 2013-05-14 13:15:59

回答

2

您需要申请格局,太:

Pattern pattern = Pattern.compile("(\\d+)\\.html"); // compiles the regex 
Matcher matcher = pattern.matcher(jcrPath);   // creates a Matcher object 
if (matcher.find()) {        // performs the actual match 
    System.out.println(matcher.group()); 
} 
+0

原因:matcher.matches()会产生错误,因为匹配需要完全匹配。 – 2013-05-14 13:17:22

+2

@JoopEggen:他没有调用'matcher.matches()',要么:) – 2013-05-14 13:17:50

+0

我的意思是'group'没有前面的'find'或'matches'就没有意义。 – 2013-05-14 13:18:50

2

Matcher#group()的Javadoc说:

返回由以前匹配所匹配的输入子序列。

这意味着你必须使用group()方法之前执行matcher.matches()matcher.find()。在你的情况下,matcher.find()将是正确的,因为matcher.matches()会检查输入字符串是否与模式相匹配整个

相关问题