-7

I want to retrieve the previous three and next three words of the searched word from a string in java. For example:

 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.

And a searched word is : jumped

I want the output as:

quick brown cat jumped over the lazy 
quick brown monkey jumped over the lazy 
  • 1
    Is this homework? What have you tried so far? Show some effort. – Arc676 Oct 28 '15 at 10:47
  • nop this is not a homework. Actually i am able to search a word from file and returned those lines that contained that word. And this is the additional requirement from my work which i am trying hard to tackle – zeeshan jamal Oct 28 '15 at 10:50
  • It doesn't matter if it's homework or home work -- this is a lazy question where you show no evidence of prior effort. – Hovercraft Full Of Eels Oct 28 '15 at 11:52

2 Answers2

0

Use the combination of \S and \s to match bot space and non-space characters.

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Does `\w` not work in Java's `Pattern`? Or are `\S` and `\s` regex patterns I haven't heard of? I thought `\s` was whitespace. – Arc676 Oct 28 '15 at 10:48
  • 1
    @Arc676 no, it should work.. `\s` for all the spaces `\S` for all the non-spaces (inverse of `\s`).. – Avinash Raj Oct 28 '15 at 10:52
  • Advantages over using `\b`? (See [here](http://stackoverflow.com/questions/11874234/difference-between-w-and-b-regular-expression-meta-characters)) – Arc676 Oct 28 '15 at 10:57
  • But if i search 'lazy' it does nothing. Can you make it in a dynamic way that i put any word and it return previous 3 and next 3 words? – zeeshan jamal Oct 28 '15 at 11:19
  • 1
    .... speaking of lazy .... what's wrong with borrowing the concept and trying to fix it yourself? `` – Hovercraft Full Of Eels Oct 28 '15 at 11:57
-1

This code will work for you :

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 
TheLostMind
  • 35,966
  • 12
  • 68
  • 104