Ainulindalë
Ainulindalë

Reputation: 171

Regex to match periods but not between numbers

I want a regex to match a string that contains a word from the previous period to the next period but if a number with a period is in in between, I want it to match the next period.

So in:

Hello. This is an example. This is an example. This is an 4.815 example.

I wanto to match:

This is an example
This is another example.
This is an 4.815 example. 

For now I have this regex but it breaks at the period in "4.815"

([^.]+)example[^.]*

Thank you!

Upvotes: 2

Views: 461

Answers (1)

The fourth bird
The fourth bird

Reputation: 163297

One option could be

[^.]*(?:(?:\.\d)[^.]*)*example[^.]*(?:(?:\.\d)[^.]*)*\.

The pattern matches

  • [^.]*(?:(?:\.\d)[^.]*)* Match any char except a dot, only when the dot is followed by a digit
  • example Match literally
  • [^.]*(?:(?:\.\d)[^.]*)* Match any char except a dot, only when the dot is followed by a digit
  • \. Match a literal dot

Regex demo

Or without the leading whitspace

(?<!\S)[^.]*(?:(?:\.\d)[^.]*)*example[^.]*(?:(?:\.\d)[^.]*)*\.

Regex demo

Upvotes: 4

Related Questions