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!
Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
\\ : Inserts a backslash This sequence inserts a backslash character in the text where it's used.
The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.
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 \\
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With