1

I want to create a regular expression for DNS.

My requirement is that the valid DNS should be:

  1. www.x.y
  2. www.t.x.y
  3. www.s.t.x.y

Only 4 dots(.) are allowed. I have tried this regular expression but its not working. Please suggest.

^[a-zA-Z0-9]+.[a-zA-Z0-9]+.[a-zA-z0-9]+.[a-zA-z0-9]$
anonymous
  • 244
  • 2
  • 4
  • 23

4 Answers4

1

A very simple regex could be something along

^www\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+(\.[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)?)?$

Three points:

  • the point (.) is a special character and must be escaped (\.)
  • we need optional clauses for the last two sections.
  • your examples start with www, so you need to include this in order to use the start mark (^)
Matten
  • 17,365
  • 2
  • 42
  • 64
1

try this link

Regular expression to match DNS hostname or IP Address?

  • Regular Expression Test Page

http://www.regexplanet.com/advanced/java/index.html

Community
  • 1
  • 1
Ran Adler
  • 3,587
  • 30
  • 27
0

try this

str.matches("www(\\.\\w+){2,4}")
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

try this regex

^(www\.|)(([a-zA-Z0-9])+\.){1,4}[a-z]+$

StNickolas
  • 576
  • 7
  • 20