Hasanthi
Hasanthi

Reputation: 1271

Java regex for word with dot

I need to a regex to validate a string like "foo.com". A word which contains a dot. I have tried several but could not get it work.

The patterns I have tried:

  1. (\\w+\\.)
  2. (\\w+.)
  3. (\\w.)
  4. (\\W+\\.)

Can some one please help me one this.

Thanks,

Upvotes: 7

Views: 13833

Answers (4)

Michal Kordas
Michal Kordas

Reputation: 10925

To validate a string that contains exactly one dot and at least two letters around use match for

\w+\.\w+

which in Java is denoted as

\\w+\\.\\w+

Upvotes: 3

Manikandan
Manikandan

Reputation: 83

I understand your question like, you need a regex to match a word which has a single dot in-between the word (not first or last).

Then below regex will satisfy your need.

^\\w+\\.\\w+$

Upvotes: 1

chitkarsh gandhi
chitkarsh gandhi

Reputation: 21

This regex works:
[\w\[.\]\\]+

Tested for following combinations:
foo.com
foo.co.in
foo...
..foo

Upvotes: 2

Pranav C Balan
Pranav C Balan

Reputation: 115282

Use regex with character class

([\\w.]+)

If you just want to contain single . then use

(\\w+\\.\\w+)

In case you want multiple . which is not adjacent then use

(\\w+(?:\\.\\w+)+)

Upvotes: 7

Related Questions