今天是我第一天学习正则表达式(在此之前从字面上看没有背景),通过书中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
*/
这是我一直在寻找的详细答案,感谢您以初学者友好的方式解释文档。我最好不使用lookAt(),而是改变我的正则表达式来使用find()? – Wrap2Win
你最好检查http://stackoverflow.com/questions/30008397/whats-the-difference-between-matcher-lookingat-and-find以获得更详细的解释 – Gearon