Java concrete regex

How to verify that String input in Java has the format:

xxxxx-xxxxx-xxxx-xxxx

where x is the number 0..9?

Thank!

+5
source share
2 answers

Java String objects have a method matchesthat can be checked against a regular expression:

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

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

+3
source

To get started, this is a great source of regular expressions: http://www.regular-expressions.info . Visit it, drink and play. In addition, the API java.util.Patternhas a concise overview of regex patterns.

: , . 4 ​​

\d{4}

:

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

, :

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

, Java, String#matches(), , .

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

, \ \, String. , \\.

+4

All Articles