6

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));
        }
Community
  • 1
  • 1
Mayr Technologies
  • 725
  • 3
  • 10
  • 19

3 Answers3

8

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".

Community
  • 1
  • 1
Wrobel
  • 1,042
  • 12
  • 21
1

Try this pattern,

\w+\s+\w+\s(\d+)\s\w+

Try this,

String str = "Nom for 3 Oscar";
Pattern pattern = Pattern.compile("\\w+\\s+\\w+\\s+(\\d+)\\s+\\w+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    Log.d("Test", matcher.group(1));
}
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
0

Try this pattern:

"\\w+\\s+\\w+\\s+(\\w+)\\s+\\w+"

Test code :

String str = "Nom for you Oscar";
Pattern pattern = Pattern.compile("\\w+\\s+\\w+\\s+(\\w+)\\s+\\w+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Do you want to intercept third strings?