Matcher.matches() matches the complete string. You can use Matcher.find to match the individual integers:

while (m.find()) {
  System.out.println(m.group(1));
}
Answer from Reimeus on Stack Overflow
🌐
Reddit
reddit.com › r/adventofcode › 2023 day 2 part a [java] regex pattern not matching
r/adventofcode on Reddit: 2023 Day 2 Part A [Java] regex pattern not matching
December 3, 2023 -

First time posting here, let me know if I need to edit post to conform to any rules. My issue is that I'm trying to match regex pattern to separate out the number of cubes drawn and its color but my Matcher object seems to not be returning any matches so it's throwing a no match found exception when I try to call digitMatcher.group(). I have tested my regex pattern on sites like regexr and it seems to pass there but it's not working for some reason here. I use the same type of regex on day one and it work there so I'm not sure where my regex pattern is failing here. I'm talking about specifically in my isGameValid() method where I create a matcher base on a pattern I made above. Through debugging I know that I separated the string color pairing correctly and that my Matcher object has the correct regex pattern, it's just not matching for some reason. Any help would be appreciated. Code below:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.Integer.parseInt;
import static java.lang.Integer.sum;

public class dayTwoA {

    public static final Map<String, Integer> map = Map.of( // Mapping of digits to their letter spelling.
            "red", 12,
            "green", 13,
            "blue", 14
    );
    public static final Pattern colorPattern = Pattern.compile("blue|green|red");
    public static final Pattern digitPattern = Pattern.compile("[0-9]|[0-9][0-9]");
    public static int gameID = 0;

    public static void main(String[] args) throws FileNotFoundException {

        int sumGamesID = 0; // Sum of all the game ID.
        // Create a scanner to get input from file.
        Scanner inputFile = new Scanner(new File("src/dayTwoData.txt"));
        // Parse file for data.
        while (inputFile.hasNextLine()) {
            String inputLine = inputFile.nextLine(); // Grab next line of input.
            if (isGameValid(inputLine)) {
                sumGamesID += gameID;
            };

        }
        System.out.println("The sum of the ID of the games is  " + sumGamesID);

    }

    private static boolean isGameValid(String inputLine) {
        String gameDraws = inputLine.substring(inputLine.indexOf(":") + 1);
        gameID++; // Increment game ID.
        StringTokenizer separateDraw = new StringTokenizer(gameDraws, ";");
        while (separateDraw.hasMoreTokens()) {
            String draw = separateDraw.nextToken();
            StringTokenizer numColor = new StringTokenizer(draw, ",");
            while (numColor.hasMoreTokens()) {
                String numColorPair = numColor.nextToken();
                Matcher digitMatcher = digitPattern.matcher(numColorPair);
                int numCubes = parseInt(digitMatcher.group());
                Matcher colorMatcher = colorPattern.matcher(numColorPair);
                String color = colorMatcher.group();
                System.out.println(numCubes + "-" + colorMatcher.group());
                if (numCubes > map.get(color)) {
                    return false;
                }
                System.out.println(numColorPair);
            }
        }
        return true;
    }

}
match . but not ... Jan 6, 2026
r/regex
8mo ago
[Java] Regex, Pattern, Matcher? Mar 4, 2015
r/learnprogramming
11y ago
regex: what am I doing wrong? Jun 19, 2025
r/jdownloader
last yr.
More results from reddit.com
🌐
Alvin Alexander
alvinalexander.com › blog › post › java › java-pattern-matching-matches-method-not-working
Why isn't the Java matches method working? (Java pattern matching) | alvinalexander.com
March 13, 2019 - Solution: The important thing to remember about this Java matches method is that your regular expression must match the entire line. Specifically, a regex pattern like the following one will not work with the matches method when you work on a larger line of input text:
Discussions

Java regex does not match as expected - Stack Overflow
Not sure about the down-votes. I've tried to provide a suitable answer for you though... :) ... It is a dupe of Difference between matches() and find() in Java Regex. ... Matcher.matches returns true only if the ENTIRE region matches the pattern. More on stackoverflow.com
🌐 stackoverflow.com
Java Regex pattern not matching - Stack Overflow
I have a .txt file and at the end there is a marker "Home" and I want to take all text after the Home marker till the end of file. But in few cases I have a situation that after the text that I wan... More on stackoverflow.com
🌐 stackoverflow.com
Java Pattern does not match RegEx - Stack Overflow
You forgot to call m.find() or ... does not work. The find() should return true if the pattern is matched. Only in this case group() will return what you are expecting. ... EDIT Concerning to what method to call: find() or matches(). find() looks for the pattern in part of string, matches() matches full string. They relate like contains() and equals() of strings. I personally prefer to use find() because in this case the regex fully defines ... More on stackoverflow.com
🌐 stackoverflow.com
JAVA - Pattern regex matcher not matching - Stack Overflow
You can try it, "[email protected]" would match, and "totally_invalid_email@%*.com" would not. I believe that the reason why your regex is rejecting everything is because you seem to have extra .s in your code. If you want [email protected], then ".+@.+\\..+" would be the proper regex in that case. For more on java patterns... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › regex › Pattern.html
Pattern (Java Platform SE 8 )
July 21, 2026 - The array returned by this method ... the input. If this pattern does not match any subsequence of the input then the resulting array has just one element, namely the input sequence in string form....
🌐
Stack Overflow
stackoverflow.com › questions › 44270804 › java-regex-pattern-not-matching
Java Regex pattern not matching - Stack Overflow
so when I run it I have: error app crashes, I have to change to m.group(0) and then I have : Found value: whole text from file oh and it's not 3 empty lines, sometimes it's 3 sometimes more like 7 2017-05-30T20:06:49.793Z+00:00 ... if I use this one: Home\\s(.*?)(?=\n{3}|$) and add DOTALL to pattern I have NO MATCH 2017-05-30T20:08:47.113Z+00:00 ... Try again with updated regex in answer: Home\\s(.*?)(?=\\n{3}|$) so that it works with m.group(1) and extracts just what you need.
Top answer
1 of 3
7

You can't ask a Matcher to give a .group() unless you have called a method which asks the Matcher to operate on the input: one of .find() (preferred), .lookingAt() or .matches().

This is why you get an IllegalStateException.

As to the differences between the three, while the javadoc tells it all, just a quick reminder:

  • .find() does "real" regex matching: it will try and match the regex anywhere in the input text;
  • .lookingAt() adds the constraint that the pattern should match at the beginning of the input text;
  • .matches() is a misnomer since in addition to the constraint imposed by .lookingAt(), it also required that the full input text (the "entire region" in the javadoc) is matched.

Please also recall that those three methods return a boolean depending on whether the match was successful; if the result is false, you can't .group().

2 of 3
3

You forgot to call m.find() or m.matches(). This is mandatory, otherwise group() does not work.

The find() should return true if the pattern is matched. Only in this case group() will return what you are expecting.

So, modify your code as following:

....
if (!m.find()) {
    return;
}
String url = m.group();
...

EDIT Concerning to what method to call: find() or matches(). find() looks for the pattern in part of string, matches() matches full string. They relate like contains() and equals() of strings.

I personally prefer to use find() because in this case the regex fully defines the behavior. If I want to match full string I use ^ and $.

🌐
Stack Overflow
stackoverflow.com › questions › 41356443 › java-pattern-regex-matcher-not-matching
JAVA - Pattern regex matcher not matching - Stack Overflow
You can try it, "[email protected]" would match, and "totally_invalid_email@%*.com" would not. I believe that the reason why your regex is rejecting everything is because you seem to have extra .s in your code. If you want [email protected], then ".+@.+\\..+" would be the proper regex in that case. For more on java patterns, see https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Find elsewhere
🌐
Devwithus
devwithus.com › regex-not-match-java
Regex Not Match String In Java | devwithus.com
March 13, 2023 - Conversely, when a particular string does not match a regex, we say that it’s a “not match”. In other words, it’s a way to denote that the pattern defined by the regular expression does not appear in the input string.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › regex › Pattern.html
Pattern (Java Platform SE 7 )
Trailing empty strings are therefore not included in the resulting array. The input "boo:and:foo", for example, yields the following results with these expressions: ... Returns a literal pattern String for the specified String. This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning. ... Java™ Platform Standard Ed.
🌐
Stack Overflow
stackoverflow.com › questions › 33716000 › java-regex-pattern-matcher-not-returning-desired-results
Java regex.pattern matcher not returning desired results - Stack Overflow
May 24, 2017 - You need to remove the delimiters and global modifier from your regular expression, Java does not use this syntax. Also, instead of three group constructs, I would utilize a character set.