Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Particular java regular expression

Tags:

java

regex

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!

like image 864
Danny King Avatar asked Feb 22 '10 23:02

Danny King


People also ask

What does \\ mean in Java regex?

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.

How do you specify in 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).

What is the use of \\ in Java?

\\ : Inserts a backslash This sequence inserts a backslash character in the text where it's used.

What does \\ mean in regex?

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.


1 Answers

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

like image 70
BalusC Avatar answered Sep 23 '22 00:09

BalusC