在Java中查找字符串中的单词 [英] Finding words within a string in Java
问题描述
我本质上是用Java编写"grep",但我不认为我理解这些约定.假定以下代码块:
I am essentially writing "grep" in Java and don't think I understand the conventions. Assume the following code block:
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"
The above code prints out "false"
据我了解,模式"this"应该在字符串此文件有一行"中找到
To my understanding, the pattern "this" should be found in the string "this file has one line"
语法或理解Pattern或Matcher约定时是否出错?
Is it an error in my syntax or in my understanding of the conventions of Pattern or Matcher?
给出代码:
Matcher m = MY_PATTERN.matcher("FOO[BAR]");
while (m.find()) {
String s = m.group(1);
// s now contains "BAR"
}
如何检索包含指定模式的整行?
How could you retrieve the whole line that contains the denoted pattern?
推荐答案
Matcher.matches()
returns true if and only if the whole string matches the given regex.
如果要查找部分匹配项,则可以选择:
If you are looking for a partial match, you have the choice:
- 修改您的正则表达式:
Pattern.compile(.* this.*")
或 - 使用
Matcher.find()
:System.out.println(m.find());
或 - 使用
String.contains()
,如果您不需要正则表达式的功能,而是在寻找字面上的部分匹配项.
这篇关于在Java中查找字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!