parker parker -4 years ago 122
Java Question

attempting to return a range of words in a string using regex java

I am trying to return a range of words in string using regular expressions but i am lost in between the lines of doing it. This is my attempt

private static final String REGEX = "\\hello";
private static final String INPUT = "I love holidays hello how are you today during summer";


public static void main( String args[] ) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;

while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());

System.out.println("value of m >> "+m);//to print >>> hello how are you


Does anyone know how I can return this word hello how are you from the string using regex

Answer Source

Since the requirement is to start at hello and end at the first you you could use the following expression: hello.*?you.

Here .*? means you want to match anything but as little as possible. This is meant to stop at the first you rather than the the last.

If you want to prevent matches on input where hello and you are only parts of other words surround them with the word boundary \b: \bhello\b.*?\byou\b.

If you want to match inside sentences only, i.e. the match should not include ., ! or ?, you could use a negative character class like [^.!?], i.e. replace .*? with [^.!?]*?. Note that inside the character class . has a literal meaning, i.e. it is the dot and not the "any character" wildcard.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download