How would I check that a String input in Java has the format:
开发者_StackOverflow中文版xxxx-xxxx-xxxx-xxxx
where x is a digit 0..9?
Thanks!
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 \\
.
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.
精彩评论