How to get an specific extract from a String?

567 Views Asked by At

I want to get an extract from a String. The extract should contain the 2 words in front of the keyword and the 2 words behind the keyword. If the 2 words doesn't exist, the sentence should just end.

Example:

The word im looking for is "example".

Existing Strings:

String text1 = "This is an example.";
String text2 = "This is another example, but this time the sentence is longer";

Result:

text1 should look like this:

is an example.

text2 should look like this:

is another example, but this

How can I do this?

2

There are 2 best solutions below

0
On BEST ANSWER

Try to use Pattern:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        String text1 = "This is an example.";
        String text2 = "This is another example, but this time the sentence is longer";
        String key = "example";
        String regex = "((\\w+\\s){2})?" + key +"([,](\\s\\w+){0,2})?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text1);
        matcher.find();
        System.out.println(matcher.group(0));
        matcher = pattern.matcher(text2);
        matcher.find();
        System.out.println(matcher.group(0));
    }
}

output:

is an example

is another example, but this

mayby you will need to change regex a little bit, but you can try with this one.

0
On

Using replaceAll(), you can do it in one line:

String target = text1.replaceAll(".*?((\\w+\\W+){2})(example)((\\W+\\w+){2})?.*", "$1$3$4");

fyi, \w means "word character" and \W means "non word character"