Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex for word with dot

Tags:

java

regex

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,

like image 659
Hasanthi Avatar asked Aug 26 '16 05:08

Hasanthi


People also ask

How do I express a dot in regex?

You can then use \. \. or \. {2} to match exactly 2 dots.

What is Dot in regex in Java?

JavaObject Oriented ProgrammingProgramming. The subexpression/metacharacter “.” matches any single character except a newline.

Is dot a special character in regex?

If you want the dot or other characters with a special meaning in regexes to be a normal character, you have to escape it with a backslash. Since regexes in Java are normal Java strings, you need to escape the backslash itself, so you need two backslashes e.g. \\.

Is dot a special character in Java?

Java Example to Split String by Dot The examples are pretty much similar to splitting String by any delimiter, with only a focus on using the correct regular expression because the dot is a special character in Java's regular expression API. That's all about how to split a String by dot in Java.


4 Answers

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+)+)
like image 176
Pranav C Balan Avatar answered Sep 16 '22 22:09

Pranav C Balan


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

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

like image 38
chitkarsh gandhi Avatar answered Sep 18 '22 22:09

chitkarsh gandhi


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+
like image 26
Michal Kordas Avatar answered Sep 20 '22 22:09

Michal Kordas


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+$
like image 22
Manikandan Avatar answered Sep 19 '22 22:09

Manikandan