5

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

vrbilgi
  • 5,703
  • 12
  • 44
  • 60

3 Answers3

15

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

Frode Akselsen
  • 616
  • 2
  • 8
  • 23
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

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:

  1. Use s.split("Input") instead, it gives you an array of the substrings between occurences of "Input"
  2. Use Matcher.find() and Matcher.group(int). But be aware that your current expression will match everything after the first occurence of "Input", so you should change your expression.

Greetings, Jost

Jost
  • 5,948
  • 8
  • 42
  • 72
0
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) ); 
         }
    }
}
stacker
  • 68,052
  • 28
  • 140
  • 210