vkGunasekaran
vkGunasekaran

Reputation: 6814

How to match two or more dots in a string using regular expression

I need to capture strings containing more than one dot. String will mostly contains domain names like example.com, fun.example.com, test.funflys.com.

How can I do this using regex?

Upvotes: 5

Views: 28999

Answers (5)

Siddharth Gupta
Siddharth Gupta

Reputation: 9

Pattern.matches("[^\\.]+\\.[^\\.]+", "any_String")

  1. Gives 'false' if there are more than one dots in a String.
  2. Gives 'false' if there are dots in a starting or ending of the String.
  3. Gives 'false' for empty string String.

Upvotes: -1

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Try this one :

(.*\.)+.*

or this one (to specifically match "characters" and just... anything) :

(\w*\.)+\w*

Demo :

http://regexr.com?38ed7

Upvotes: 2

Daniël Knippers
Daniël Knippers

Reputation: 3055

This is with JavaScript.

var regex = /(\..*){2,}/;

regex.test("hello.world."); // true
regex.test("hello.world"); // false
regex.test("."); // false
regex.test(".."); // true

It searches for the pattern 'dot followed by anything (or nothing)', repeated 2 or more times.

Upvotes: 5

woutervs
woutervs

Reputation: 1510

^[A-Za-z0-9]*([A-Za-z0-9]*|\.+)+$

This will capture words or digits followed by at least one . and that can be repeated as many times.

Would be captured: hello.world.something hello......world.world something.09hello...hello

If you provide some more examples on what can and what can't be captured we can update this regex.

Upvotes: 0

utdemir
utdemir

Reputation: 27266

You should escape dot's because they have special meaning.

So, that regex would be;

.*\..*\..*

But you should be careful that \ is possibly have a special meaning on your programming language too, you may be have to escape them also.

Upvotes: 5

Related Questions