2012-03-05 52 views
0

我正在学习正则表达式和更具体的单词边界。我有一段代码,我觉得应该返回至少一个匹配,但它不是。试图理解单词边界

什么是错的代码我用

public static void main(String[] args) 
{ 
    boolean matches; 
    String [] various = {"Men of honour", "X Men", "Children of men", "Company men are great"}; 

    for(int i = 0; i < various.length; i++) 
    { 
     matches = Pattern.matches("\\bMen", various[i]); 

     System.out.println("Does the string match the pattern? " + matches); 
    } 



} 

放出来是遵循

Does the string match the pattern? false 
Does the string match the pattern? false 
Does the string match the pattern? false 
Does the string match the pattern? false 

回答

1

当您使用.matches(),你问的正则表达式引擎,如果你的模式整个输入字符串相匹配。但是,您想知道您的模式是否可以在输入字符串内找到。

用途:

Pattern.compile("\\bMen").matcher(various[i]).find() 
5

这是因为字边界的不。这是因为.matches()方法需要整个字符串匹配。它不能提取子匹配。

你想要的东西像

Pattern regex = Pattern.compile("\\bMen", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); 
for(int i = 0; i < various.length; i++) 
{ 
    Matcher regexMatcher = regex.matcher(various[i]); 
    matches = regexMatcher.find(); 
    System.out.println("Does the string match the pattern? " + matches); 
}