2016-11-13 53 views
1

今天是我第一天学习正则表达式(在此之前从字面上看没有背景),通过书中Thinking in Java 4th Edition一章中的Strings一章。我拉我的头发为什么正则表达式不匹配输入字符串的任何区域。我已经在regex101中测试过了,我得到了我期望的结果,但是在Java中(你不能在regex101网站上测试),结果是不同的。
编辑:一章中做运动10非常简单的Java正则表达式没有给出预期的结果

正则表达式:n.w\s+h(a|i)s
输入字符串:Java now has regular expressions
预期成果:在输入字符串
实际结果的区域"now has"找到匹配:没有找到匹配

我的相关代码:

import java.util.regex.*; 

public class Foo { 
    public static void main(String[] args) { 
    // NOTE: I've also tested passing the regex as an arg from the command line 
    //  as "n.w\s+h(a|i)s" 
    String regex = "n.w\\s+h(a|i)s"; 
    String input = "Java now has regular expressions"; 

    Pattern p = Pattern.compile(regex); 
    Matcher m = p.matcher(input); 

    // Starting at the beginning of the input string, look for a match in ANY 
    // region of the input string 
    boolean matchFound = m.lookingAt(); 
    System.out.println("Match was found: " + matchFound); 
    } 
} 
/* OUTPUT 
-> Match was found: false 
*/ 

回答

1

使用m.find()代替m.lookingAt()

可以打印你所得到的由m.group()

请在下面校验码。

import java.util.regex.*; 

public class Foo { 
    public static void main(String[] args) { 
     // NOTE: I've also tested passing the regex as an arg from the command 
     // line 
     // as "n.w\s+h(a|i)s" 
     String regex = "n.w\\s+h(a|i)s"; 
     String input = "Java now has regular expressions"; 

     Pattern p = Pattern.compile(regex); 
     Matcher m = p.matcher(input); 

     // Starting at the beginning of the input string, look for a match in 
     // ANY 
     // region of the input string 
     boolean matchFound = m.find(); 
     System.out.println("Match was found: " + matchFound); 
     System.out.println("Matched string is: " + m.group()); 
    } 
} 

lookingAt的的JavaDoc()是

公共布尔lookingAt()

尝试匹配输入序列,开始于 区域的开始,针对所述图案。像匹配方法一样,这个方法 总是从该区域的开始处开始;与该方法不同,它不需要整个区域匹配。

如果匹配成功,则可以通过 开始,结束和组方法获取更多信息。

返回:当且仅当输入序列的前缀匹配 此匹配器模式

这意味着,这种方法需要正则表达式在输入字符串的最开始匹配。

这种方法不经常使用,效果就像你修改你的正则表达式为"^n.w\\s+h(a|i)s",并使用find()方法。它还会限制正则表达式在输入字符串的最开始处匹配。

+0

这是我一直在寻找的详细答案,感谢您以初学者友好的方式解释文档。我最好不使用lookAt(),而是改变我的正则表达式来使用find()? – Wrap2Win

+0

你最好检查http://stackoverflow.com/questions/30008397/whats-the-difference-between-matcher-lookingat-and-find以获得更详细的解释 – Gearon

2

使用boolean matchFound = m.find();代替boolean matchFound = m.lookingAt();

从Javadoc中

lookingAt()尝试匹配输入序列,开始于区域的开始,针对所述图案。

+0

完美地工作,如果你能解释为什么lookingAt()不按我想的方式工作,我会接受这个答案。 – Wrap2Win

+0

如果你的输入字符串是''现在有正则表达式'''那么lookingAt将返回true。 – iNan

+0

@RNGesus [文档](https://docs.oracle。com/javase/8/docs/api/java/util/regex/Matcher.html)解释了Matcher方法之间的区别。 – VGR

相关问题