vrbilgi
vrbilgi

Reputation: 5793

regular expression java

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

Upvotes: 5

Views: 15974

Answers (3)

Mark Byers
Mark Byers

Reputation: 838036

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

Upvotes: 15

stacker
stacker

Reputation: 68942

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) ); 
         }
    }
}

Upvotes: 0

Jost
Jost

Reputation: 5840

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

Upvotes: 2

Related Questions