I am trying to Take the content between Input, my pattern is not doing the right thing please help.
below is the sudocode:
s=\"Input one Input Two In
this does not work, because m.matches is true if and only if the whole string is matched by the expression. You could go two ways:
Greetings, Jost
import java.util.regex.*;
public class Regex {
public static void main(String[] args) {
String s="Input one Input Two Input Three";
Pattern pat = Pattern.compile("(Input) (\\w+)");
Matcher m = pat.matcher(s);
while( m.find() ) {
System.out.println( m.group(2) );
}
}
}
Use a lookahead for Input
and use find
in a loop, instead of matches
:
Pattern pattern = Pattern.compile("Input(.*?)(?=Input|$)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
See it working online: ideone
But it's better to use split here:
String[] result = s.split("Input");
// You need to ignore the first element in result, because it is empty.
See it working online: ideone