tags:

views:

80

answers:

2

Hi,

How would I check that a String input in Java has the format:

xxxx-xxxx-xxxx-xxxx

where x is a digit 0..9?

Thanks!

+3  A: 

String objects in Java have a matches method which can check against a regular expression:

 myString.matches("^\\d{4}(-\\d{4}){3}$")

This particular expression checks for four digits, and then three times (a hyphen and four digits), thus representing your required format.

Joey
Note: I edited it just again because I left out the anchors. Use the anchored version, not the one without.
Joey
Why couldn't this be reduced to :myString.matches("(-\\d{4}){4}");
Amir Afghani
@Amir: Because your string would have to start with a hyphen then.
Joey
Contra-nitpick: Java regexps are by default anchored `;)`
BalusC
@Balus: Eek! Ok, that's news to me. Though to be fair I never used them in Java so far anyway. So out of curiosity: How do you do an unanchored match, then? Pre- and append `.*`?
Joey
+4  A: 

To start, this is a great source of regexps: http://www.regular-expressions.info. Visit it, poke and play around. Further the java.util.Pattern API has a concise overview of regex patterns.

Now, back to your question: you want to match four consecutive groups of four digits separated by a hyphen. A single group of 4 digits can in regex be represented as

\d{4}

Four of those separated by a hyphen can be represented as:

\d{4}-\d{4}-\d{4}-\d{4}

To make it shorter you can also represent a single group of four digits and three consecutive groups of four digits prefixed with a hyphen:

\d{4}(-\d{4}){3}

Now, in Java you can use String#matches() to test whether a string matches the given regex.

boolean matches = value.matches("\\d{4}(-\\d{4}){3}");

Note that I escaped the backslashes \ by another backslash \, because the backslashes have a special meaning in String. To represent the actual backslash, you'd have to use \\.

BalusC
They don't have a special meaning to the String class. They have a special meaning for the compiler.
Joey
Geez, I put 3 minutes of effort in and there's already an accepted answer.
BalusC
@Johannes: thank you for the nitpick :)
BalusC
+1 for the effort, though. I tend to no longer do that with trivial questions exactly for that reason ;-). Except for batch files where I still have a hope of being the first to answer correctly and thoroughly :-)
Joey