Search code examples
javaandroidregexstringillegalstateexception

Java Regex Extract String between two Strings


The problem

I have a pattern like this "Nom for ? oscars" or "Nom for 2 Golden Globes. Nom for ? oscars. 30 wins 18 nominations" And I want to determine the ? with regex, so the amount of oscars.

What I tried

It seems like there

Corresponding to this questions: Extract string between two strings in java and

How do I find a value between two strings? I tried this pattern:

final Pattern pattern = Pattern.compile("for(.*?)Oscar");

Next I tried this following this question: Java - Best way to grab ALL Strings between two Strings? (regex?)

  final Pattern pattern = Pattern.compile(Pattern.quote("Nom") +"(.*?)"+ Pattern.quote("Oscar"));

The rest of my code:

final Matcher matcher = pattern.matcher("Nom for 3 Oscar");
    while(matcher.find()){

    }
Log.d("Test", matcher.group(1));

All of these pattern result in this exception:

java.lang.IllegalStateException: No successful match so far

I think I just oversee something very simple.

Can you guys help me ?

Edit


So the problem was that I call matcher.group(1) after the loop. I missunderstood the working of the find method. However this code is working indeed, when i call matcher.group(1) inside the loop.

   final Pattern pattern = Pattern.compile("for(.*?)Oscar");
    final Matcher matcher = pattern.matcher("Nom for 3 Oscar");
        while(matcher.find()){
         Log.d("Test", matcher.group(1));
        }

Solution

  • I write test as in Extract string between two strings in java and this is working. I think Your input string don't matches:

     @Test
            public void regex() {
                String str = "Nom for 3 Oscar, dom for 234235 Oscars";
                Pattern pattern = Pattern.compile("for(.*?)Oscar");
                Matcher matcher = pattern.matcher(str);
                while (matcher.find()) {
                    System.out.println(matcher.group(1));
                }
            }
    

    Output:

        3 
     234235 
    

    After my answer You edited Your question and I see, in Your input String "oscar" starts with lowecase "o", in Pattern with uppercase "O".