Need to build a regular expression for the following:
x.x.x.x
Above represents some host name, where x could be a group of characters/numbers and there must be only 3 dots.
I tried few things but was failing in some cases.
Need to build a regular expression for the following:
x.x.x.x
Above represents some host name, where x could be a group of characters/numbers and there must be only 3 dots.
I tried few things but was failing in some cases.
You can try with this one:
String regex = "[a-z0-9]+[\\.]{1}[a-z0-9]+[\\.]{1}[a-z0-9]+[\\.]{1}[a-z0-9]+";
Explained:
[a-z0-9]+ matches a group or characters/numbers with minimal length of 1.[\\.]{1} matches exactly one . sympol. The {1} denotes a length of 1, but you can use [.] or \\., as well.As @Calvin Scherle mentioned, you can shorten the regex to:
String regex = "\\w+\\.\\w+\\.\\w+\\.\\w+";
Explained:
\w+ will match every group of word characters (including letters and digits) with minimal length of 1\. will match the . symbol\ is a metacharacter and has to be escaped and thus we'll have \\w+ and \\.You could test with String.matches("[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+")
It will match any alphanumeric characters separated by 3 dots.
[a-zA-Z0-9] is a group matching any alphanumeric characters.+ means "look for one or more occurences"\\. means the literal . characterTry this:
String regex = "[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]"