在Java中查找字符串中的单词 [英] Finding words within a string in Java

查看:116
本文介绍了在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:

这篇关于在Java中查找字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆