Matcher.matches returns true only if the ENTIRE region matches the pattern.

For the output you are looking for, use Matcher.find instead


Explanation of each case:

Pattern p = Pattern.compile("[^A-Z]+");
Matcher matcher = p.matcher("GETs");
  if (matcher.matches()) {

Fails because the ENTIRE region 'GETs' isn't lowercase


Pattern p = Pattern.compile("[A-Z]+");
Matcher matcher = p.matcher("GETs");
  if (matcher.matches()) {

This fails because the ENTIRE region 'GETs' isn't uppercase


Pattern p = Pattern.compile("[A-Z]+");
Matcher matcher = p.matcher("GET");
  if (matcher.matches()) {

The ENTIRE region 'GET' is uppercase, the pattern matches.

Answer from Pineda 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;
    }

}
Discussions

Java Pattern not matching RegEx - Stack Overflow
Because your regex doesn't match the string, there are other characters before (and after) the \d matches after all. ... Save this answer. ... Show activity on this post. matches() method attempts to match the whole string, but you need just digit occurrences in it. You need to use find() method and you might need to use while operator instead of if because it shifts matcher ... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
Java regex matcher not matching - Stack Overflow
In your exact case you should call Matcher.find(), since your regex won't match against the entire input, which is what Matcher.matches() checks for. ... Save this answer. ... Show activity on this post. If you using Java > 7. More on stackoverflow.com
🌐 stackoverflow.com
Java Regex not matching properly - Stack Overflow
I need to check if a string has any equals sign on its own. My current regex does not seem to work within Java, even though RegexPal matches it. My current code is: String str = "test=tests"; Sy... More on stackoverflow.com
🌐 stackoverflow.com
Simple java regex not matching - Stack Overflow
Regex matching is done using .find(): Copyfinal Matcher matcher = patt.matcher("a 18c1"); if (matcher.find()) System.out.println(matcher.group()); ... Ok, then i am trying to call patt.matcher("a 18c1").group() , it returning java.lang.IllegalStateException: No match found 2014-03-18T13:15... More on stackoverflow.com
🌐 stackoverflow.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 - Modify your regex pattern to match the entire String, and keep using the matches method. Modify your Java program to use the find method of the Matcher class instead of using the matches method.
🌐
Devwithus
devwithus.com › regex-not-match-java
Regex Not Match String In Java | devwithus.com
March 13, 2023 - So, the regular expression to match any string that does not contain the above letters would be: boolean doesMatch = "dev with us".matches("[^dev]*"); System.out.println(doesMatch); // false · Please bear in mind that when the anchor ^ is placed out of the brackets, it means that the regex should match the beginning of the string. Basically, we can use a negative lookahead assertion to answer our central question. Here’s another Java example of how we can use a negative lookahead to match all strings except “devwithus”:
🌐
Stack Overflow
stackoverflow.com › questions › 22480437
Simple java regex not matching - Stack Overflow
Regex matching is done using .find(): Copyfinal Matcher matcher = patt.matcher("a 18c1"); if (matcher.find()) System.out.println(matcher.group()); ... Ok, then i am trying to call patt.matcher("a 18c1").group() , it returning java.lang.IllegalStateException: No match found 2014-03-18T13:15...
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › regex › Pattern.html
Pattern (Java Platform SE 8 )
July 21, 2026 - Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match. Groups beginning with (? are either pure, non-capturing groups that do not capture text and do not count towards the group total, or named-capturing group. This class is in conformance with Level 1 of Unicode Technical Standard #18: Unicode Regular Expression, plus RL2.1 Canonical Equivalents. Unicode escape sequences such as \u2014 in Java source code are processed as described in section 3.3 of The Java™ Language Specification.
🌐
Reddit
reddit.com › r/javahelp › regex doesn't match even though regex101 & intellj's regex tester confirm that it should work
r/javahelp on Reddit: RegEx doesn't match even though regex101 & IntellJ's RegEx tester confirm that it should work
March 28, 2018 -

SOLVED: I have still no idea what was wrong but it is working now... Thanks to everyone.

Hello,

I am currently trying to match the content of a packet, unfortunately, the regex doesn't match. I tested it on regex101.com (https://regex101.com/r/AGUVr4/1/) and IntelliJ offers a tester as well, it confirmed it confirmed that it is working as well. However, when I run my code, it doesn't match.

^(.+)(Host: launcher2\\.robertsspaceindustries\\.com).+(User-Agent: libcurl-agent\\/[0-9]\\.[0-9]).+(Accept: application\\/json).+(Content-Type: application\\/json).+(Content-Length: [0-9]+)(.+)$

Code: https://hastebin.com/suloguxifa.java

Any help is welcome.

🌐
Stack Overflow
stackoverflow.com › questions › 79586498 › java-regex-not-matching
java regex not matching - Stack Overflow
Pattern pattern = Pattern.compile("^kb|KB(\\d{3})\\.pdf"); Matcher matcher = pattern.matcher("kb165.pdf"); if(matcher.matches()) { System.out.println("YAY"); }else { System.out.println("OH NO"); } can anyone please explain, why the regex from the debugger in correct format ("\" got transformed in the debugger to the resulting "") as it shows to me: ... Try "^(kb|KB)(\\d{3})\\.pdf" because regex concatenation (ab) binds stronger than regex alternation (a|b). ... Your regex101 example works, but not as you expect.
🌐
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