Jefe infiltrado
Jefe infiltrado

Reputation: 382

regex for a whole word containing dots within a sentence

I am looking for a regular expression to catch a whole word or expression within a sentence that contains dots:

this is an example test.abc.123 for what I am looking for

In this case i want to catch "test.abc.123"

I tried with this regex:

(.*)(\b.+\..++\b)(.*)

but it gets me: "abc.123 for what I am looking for"

I see that I got something completely wrong, can anyone enlighten me?

Upvotes: 0

Views: 2275

Answers (3)

revo
revo

Reputation: 48731

If you need to match part of a string you don't need to match entire string (unless you are restricted by a functionality).

Your regex is so greedy. It also has dots every where (.+ is not a good choice most of the time). It doesn't have a precise point to start and finish either. You only need:

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

It looks for strings that begin and end with word characters and contain at least a period. See live demo here

Upvotes: 2

guygrinberger
guygrinberger

Reputation: 327

This regex pattern matches strings with two or more dots:

.*\..*\..*

"." matches any character except line-breaks "*" repeats previous tokens 0 or more times "." matches a single dot, slash is used for escape

.* Match any character and continue matching until next token

test.abc.123

(.) Match a single dot

test. abc.123

.* Again, any character and continue matching until next token

test.example.com

. Matches a single dot

test.example. com

.* Matches any character and continue matching until next token

test.example.com

Upvotes: 0

Michał Turczyn
Michał Turczyn

Reputation: 37367

Try this pattern: (?=\w+\.{1,})[^ ]+.

Details: (?=\w+\.{1,}) - positive lookahead to locate starting of a word with at least one dot (.). Then, start matching from that position, until space with this pattern [^ ]+.

Demo

Upvotes: -1

Related Questions