2012-04-26 126 views
2

我想匹配一个字符,例如'如果它之前没有角色\'。Java正则表达式问题

有效État de l\'impression

无效État de l'impression

有效Saisir l\'utilisateur et le domaine pour la connexion

我相信我以后是类型的声明,如负回顾后?

例如(?<!\\)'我在RegexBuilder

但问题是,当我试图在Java的

这项工作

代码正在测试,工作正常

String[] inputs = new String[] { "Recherche d'imprimantes en cours…", "Recherche d\\'imprimantes en cours…" } ; 

for(String input : inputs) 
{ 
    Pattern p = Pattern.compile("(?<!\\\\)'"); 
    System.out.println(input); 
    System.out.println(p.matcher(input).matches()); 
} 

输出

Recherche d'imprimantes en cours… 
false 
Recherche d\'imprimantes en cours… 
false 

哪一个应该匹配true,false

+0

可能只是简单使用 “任何东西,但这个”'[^ \\\\]'右侧的“ – delicateLatticeworkFever 2012-04-26 11:36:09

+0

@goldilocks之前,但不会匹配,如果一个(未转义的!)报价在输入字符串的开头。换句话说,''pattern.compile(“[^ \\\\'''))matcher(”'“)。find()'将返回'false',而引号之前没有反斜杠。 – 2012-04-26 11:44:39

+0

啊,很好。傻我。负面的后顾之道确实有效。 – delicateLatticeworkFever 2012-04-26 11:50:36

回答

3

p.matcher(input).matches()验证整个输入。改为尝试p.matcher(input).find()

1

正则表达式应该可以正常工作,但Matcher#matches()不能正常工作,因为您认为它正常工作。它只返回表达式匹配整个字符串的真。

从JavaDoc的上Matcher#matches()

尝试来匹配图案的整个区域。

2

不要在循环中对同一模式使用Pattern.compile() - 它会破坏“编译”的目的。

String[] inputs = new String[] { 
    "Recherche d'imprimantes en cours…", 
    "Recherche d\\'imprimantes en cours…" 
}; 
Pattern pat = Pattern.compile("(?<!\\\\)'"); 

for (String s : inputs) { 
    Matcher mat = pat.matcher(s); 
    while (mat.find()) { 
     System.out.format("In \"%s\"\nFound: \"%s\" (%d, %d)\n", 
      s, mat.group(), mat.start(), mat.end()); 
    } 
} 

输出:

In "Recherche d'imprimantes en cours…" 
Found: "'" (11, 12)