Search code examples
regexregex-greedy

Regex to find last occurrence of pattern in a string


My string being of the form:

"as.asd.sd fdsfs. dfsd  d.sdfsd. sdfsdf sd   .COM"

I only want to match against the last segment of whitespace before the last period(.)

So far I am able to capture whitespace but not the very last occurrence using:

\s+(?=\.\w)

enter image description here

How can I make it less greedy?


Solution

  • You can try like so:

    (\s+)(?=\.[^.]+$)
    

    (?=\.[^.]+$) Positive look ahead for a dot and characters except dot at the end of line.

    Demo:

    https://regex101.com/r/k9VwC6/3