user4316384
user4316384

Reputation:

Regex match anything preceding a sequence of dots

I'd like to make a regex that matches anything that is succeeded by four points or more:

asdf....... 

Would match to asdf.

I've tried with:

.+?(?=\.{4,})

but it only discards the last four dots, so it matches asdf....

How can it be done?

Upvotes: 5

Views: 444

Answers (2)

kfairns
kfairns

Reputation: 3057

^(?!\.+)(.+?)\.{4,}$

Captures anything preceding 4 or more dots, but also makes sure that the string isn't all dots

If you're searching through a larger document:

(?!\.).+?(?<!\.)(?=\.{4,})

See here for the first example

See here for the second example

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

The .+?(?=\.{4,}) regex matches asdf in asdf....... since it finds 4 or more dots right after the value, but since the \.{4,} is inside a non-consuming pattern, the ....... remains to be checked and the first . in that substring is matched again since .+? matches any 1 or more chars other than line break chars, but as few as possible. Same happens with the second and third .s since they all are followed with 4+ commas.

What you may do is either make the dot matching part consuming and capture the .+? (then the value you need will be in Group 1):

(.+?)\.{4,}

See the regex demo

Here, (.*?) is a capturing group matching 0+ chars (use * instead of + to match 1 or more) other than line break chars and \.{4,} will match and consuming 4 or more . chars (not allowing to check for a match when inside the dots).

Upvotes: 2

Related Questions