Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression java

Tags:

java

regex

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 Input Three";
Pattern pat = Pattern.compile("Input(.*?)");
Matcher m = pat.matcher(s);

 if m.matches():

   print m.group(..)

Required Output:

one

Two

Three

like image 489
vrbilgi Avatar asked Nov 12 '11 19:11

vrbilgi


1 Answers

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

like image 51
Mark Byers Avatar answered Sep 28 '22 09:09

Mark Byers