Java Regex模式在任何在线测试程序中匹配,但在Eclipse中不匹配

我有一段代码,我无法在Eclipse上安装Java 1.7。

有一个正则表达式我想用来匹配和提取每个匹配的2个字符串,所以我使用2组。

我已经在许多网站(在线正则表达式测试人员)中测试了我的表达,并且它适用于它们,因为它不能用于Eclipse中的Java项目。

源字符串看起来像这些中的任何一个:

forms语言:isNatural

注释工具:isHuman%Human Annotator:isHuman

混合注释:conceptType%混合注释工具:conceptType%Hybrid Tagset:conceptType

… 等等。

我想提取“:”前面的第一个单词和每个匹配后面的单词。

我正在使用的正则表达式是这样的:

(\ W * \ S * \ W +):(\ S + \ W +)%{0,1}

以及代码片段:

String attribute = parts[0]; Pattern pattern = Pattern.compile("(\\w*\\s*\\w+):(\\s+\\w+)%{0,1}"); Matcher matcher = pattern.matcher(attribute); OWLDataProperty dataProp = null; if (matcher.matches()){ while (matcher.find()){ String name = null, domain = null; domain = matcher.group(1); name = matcher.group(2); dataProp = factory.getOWLDataProperty(":"+Introspector.decapitalize(name), pm); OWLClass domainClass = factory.getOWLClass(":"+domain.replaceAll(" ", ""), pm); OWLDataPropertyDomainAxiom domainAxiom = factory.getOWLDataPropertyDomainAxiom(dataProp, domainClass); manager.applyChange(new AddAxiom(ontology, domainAxiom)); } 

有谁知道为什么它不起作用?

非常感谢。

使用matches() ,您会询问您提供的字符串是否与整个正则表达式匹配。 就好像你在你的正则表达式的开头添加了^ ,最后添加了$

你的正则表达式是正常的,并返回你期望的。 我建议测试它regexplanet.com,Java模式 。 您将看到matches()为true,何时为false以及每个find()将返回的内容。

为了解决您的问题,我认为您只需要删除if (matcher.matches())条件。