试图理解单词边界

时间:2012-03-05 09:41:18

标签: java regex

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

我使用的代码有什么问题

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);
    }



}

out put如下

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

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

使用.matches()时,如果您的模式与整个输入字符串匹配,则会询问正则表达式引擎。但是,您想知道您的模式是否可以在输入字符串中的某处找到。

使用:

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