Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Regular Expressions in Java

Farha Jawed
seal-mask
.a{fill-rule:evenodd;}techdegree
Farha Jawed
Front End Web Development Techdegree Student 2,878 Points

Why am I getting correct output for "Next door to Dylan in 90210" even by not changing the regular expression pattern?

For the input "Next door to Dylan in 90210", the output for regular expression "\d{5}" is: "Next door to Dylan in 90210 is NOT a valid zip code" The code is as follows:

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Reggie {
  public static void main(String[] args) {
    Console console = System.console();
    String zipCode = console.readLine("Enter your zipcode: ");
    if(zipCode.matches("\\d{5}")) {
        System.out.printf("%s is a valid zip code%n", zipCode);
    } else {
        System.out.printf("%s is NOT a valid zip code%n", zipCode);
    }
  }
}

Input: Next door to Dylan in 90210

Output: Next door to Dylan in 90210 is NOT a valid zip code

The output seems correct. Why didn't I need to change the regular expression to "^\d{5}$" ?

1 Answer

Mike Papamichail
Mike Papamichail
4,883 Points

Hey Farha Jawed !

Although the result is logical, we wouldn't want to print out to the user the whole sentence right? We'd want to print out just the Post Code even if that's not a valid one. However in your case, you do enter a 5 digit post code(90210) so we would want to get that and only that out of the whole sentence and print out that 90210 is a valid postal code! So by leaving your regex to : "\d{5}" the method is looking to find 5 numbers in a row but instead it also finds a bunch of other words before that so even though the post code is valid , it's counted as an invalid one due to the reason i stated above. Now, if you change your regex to : "^\d{5}$" , this tells the method that out of the whole String that was passed in, you want to find the part of the String that starts and ends in numbers and specifically a 5 digit number thus ignoring the previous words and printing the correct output: 90210 is a valid zip code.

Hope this helps, let me know down below :D !