Danny King
Danny King

Reputation: 1991

Particular java regular expression

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!

Upvotes: 5

Views: 922

Answers (2)

BalusC
BalusC

Reputation: 1108642

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 \\.

Upvotes: 4

Joey
Joey

Reputation: 354416

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.

Upvotes: 3

Related Questions