【发布时间】:2015-12-16 19:18:20
【问题描述】:
我基本上是在用 Java 编写“grep”,但我认为我不理解这些约定。假设以下代码块:
public class HelloWorld {
public static void main(String[] args) {
Pattern p = Pattern.compile("this");
Matcher m = p.matcher("this file has one line");
System.out.println(m.matches());
}
}
上面的代码打印出“false”
据我了解,模式“this”应该在字符串“this file has one line”中找到
这是我的语法错误还是我对 Pattern 或 Matcher 约定的理解有误?
编辑: 给定代码:
Matcher m = MY_PATTERN.matcher("FOO[BAR]");
while (m.find()) {
String s = m.group(1);
// s now contains "BAR"
}
如何检索包含指定模式的整行?
【问题讨论】:
-
您的代码不是在字符串中寻找
"this",而是在查看该字符串是否与"this"正则表达式字符串完全匹配,但它不匹配,所以@ 987654327@ 正确返回。 -
您可能想了解String类docs.oracle.com/javase/7/docs/api/java/lang/…中的
contains -
尝试使用
find而不是matches。 -
如果您必须为此使用正则表达式,请参阅stackoverflow.com/a/600740/1413133
-
即使
grep也不在乎“文字”;echo thisissomething|grep this将打印thisissomething。消除了这种误解,您想要的是使用 .find(),而不是 .matches()。是的,.matches() 的名字很糟糕,第一次就抓住了所有人(.matches() 不进行正则表达式匹配,因为定义了正则表达式匹配)。