DylanK DylanK -4 years ago 87
Java Question

Java long regex

I'm trying to express a pattern like this

9 digits followed by an underscore, then 5 letters, another underscore, a 8-digit date, and"_1_USA".

This is what I got so far

String regex = "/^([0-9]{9})_([A-Z]{5})_(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])(20\\d\\d)(_1_USA)$/"

But it just doesn't work. I guess it's something wrong with the "_1_USA" part. Any ideas?

Answer Source

The quantity [1_USA]{1} tells Java to match any single character of 1, underscore, U, S, or A. Instead, just use a literal string:

String input = "212425762_CHECK_08182014_1_USA";
String regex = "^([0-9]{9})_([A-Z]{5})_([0-9]{8})_(1_USA)$";
if (input.matches(regex)) {
    System.out.println("The input matches.");

In addition, your regex had some other typos, such as leading and trailing forward slashes, and incorrectly closed character classes. Java, unlike some other languages, doesn't use forward slashes in its regex patterns (unless you mean them literally).


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download