0

I have some problems with the pattern in Java. I followed all of the steps in Regex but these lines of code are not working!

Pattern p = Pattern.compile("[a-zA-Z]{4}-[0-9]{1}");
        if (p.matcher(id).matches())
        this.id = id;
        else
        System.out.println("Wrong format!");

Whenever I type ABCD-0123, it is false and prints out wrong format

2 Answers2

4

[0-9]{1} means only one digit (in the end of you pattern), and you are invoking matches, which considers the whole input.

Either adjust the digits to {4} or whatever you need, or invoke find instead of matches.

The latter (find) will... find the pattern inside your given input, instead of matching against the whole input.

Useful for patterns describing part of the input.

Mena
  • 47,782
  • 11
  • 87
  • 106
  • It doesn't work for me even though I changed the code to `find` instead of `matches` – Hon Huy Ngo Jan 20 '20 at 18:33
  • An invocation of `find` with pattern `[a-zA-Z]{4}-[0-9]{1}` on `ABCD-0123` will return `true` (`group()` will return `ABCD-0`). At this point I can only suggest you debug your code and find out what the given `id` really looks like. – Mena Jan 20 '20 at 19:32
0

Replace the regex condition by [a-zA-Z]{4}-[0-9]+

  • [a-zA-Z]{4}: contains letters of the alphabet and must be exactly 4 letters.
  • Followed by a "-"
  • Then digits [0-9]+(if you want to set the size of the replace the + by {n} n is equal to the number of digits
mdev
  • 349
  • 1
  • 5
  • 1
    Not a very descriptive answer, would you mind explaining your answer and what the regex does? – Popeye Jan 20 '20 at 15:04
  • [a-zA-Z]{4}-[0-9]+ [a-zA-Z]{4}: contains letters of the alphabet and must be exactly 4 letters. Followed by a "-" Then digits [0-9]+(if you want to set the size of the replace the + by {n} n is equal to the number of digits – mdev Jan 20 '20 at 15:08
  • 1
    I was more trying to encourage you to update your answer with more detail, it wasn't really meant to be for you to add a comment. – Popeye Jan 20 '20 at 15:26