【问题标题】:Capturing the previous three and next three words from a sentence based on searched word根据搜索词从句子中捕获前三个和后三个词
【发布时间】:2016-01-28 02:28:49
【问题描述】:

我想从java中的字符串中检索搜索词的前三个和后三个词。 例如:

 I have a string:
 A quick brown cat jumped over the lazy dog.
 A quick brown monkey move over the lazy dog.
 A quick brown monkey jumped over the lazy dog.

搜索到的单词是:jumped

我希望输出为:

quick brown cat jumped over the lazy 
quick brown monkey jumped over the lazy 

【问题讨论】:

  • 这是作业吗?你都尝试了些什么?表现出一些努力。
  • 不,这不是家庭作业。实际上,我能够从文件中搜索一个单词并返回包含该单词的那些行。这是我工作中的额外要求,我正在努力解决
  • 不管是家庭作业还是家庭作业——这是一个懒惰的问题,你没有证据表明之前的努力。

标签: java regex string


【解决方案1】:

此代码将为您工作:

public static void main(String[] args) {
        List<String> l1 = new ArrayList<>();
        l1.add("A quick brown cat jumped over the lazy dog.");
        l1.add("A quick brown monkey move over the lazy dog..");
        l1.add("A quick brown monkey jumped over the lazy dog.");

        Pattern pattern = Pattern.compile("\\s((\\w+\\s){3}jumped\\s(\\w+\\s){3})");
        for (String s : l1) {
            Matcher m = pattern.matcher(s);
            while (m.find()) {
                System.out.println(m.group(1));
            }
        }

    }

O/P:

quick brown cat jumped over the lazy 
quick brown monkey jumped over the lazy 

【讨论】:

    【解决方案2】:

    使用\S\s 的组合来匹配机器人空格和非空格字符。

    Pattern.compile("(?:\\S+\\s+){3}" + search_word + "(?:\\s+\\S+){3}");
    

    DEMO

    【讨论】:

    • \w 在 Java 的 Pattern 中不起作用吗?或者是我没听说过的\S\s 正则表达式模式?我以为\s 是空格。
    • @Arc676 不,它应该可以工作.. \s 用于所有空格 \S 用于所有非空格(\s 的倒数)..
    • 使用\b的优势? (见here
    • 但如果我搜索“懒惰”,它什么也不做。你能以动态的方式让我输入任何单词并返回前 3 个和后 3 个单词吗?
    • ....说到懒惰....借用这个概念并尝试自己修复它有什么问题? &lt;/rolls_eyes&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多