java - How to get an specific extract from a String? -


i want extract string. extract should contain 2 words in front of keyword , 2 words behind keyword. if 2 words doesn't exist, sentence should end.

example:

the word im looking "example".

existing strings:

string text1 = "this example."; string text2 = "this example, time sentence longer"; 

result:

text1 should this:

is example.

text2 should this:

is example, this

how can this?

try use pattern:

import java.util.regex.matcher; import java.util.regex.pattern;  public class test {      public static void main(string[] args) {         string text1 = "this example.";         string text2 = "this example, time sentence 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 example

is example, this

mayby need change regex little bit, can try one.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -