Захар Joe
Захар Joe

Reputation: 693

Regex start searching from the end of the string (reverse)

I have strings that have blocks enclosed in underscores in them. Example:

*Text* _word_ it is something we read every day. _Words in texts_ can be really expressive. _A nice text is a pleasure for your body and soul_ (Oscar Wilde)

In the example above there are three such blocks but the number varies from string to string. I want to match only the last one, i.e. starting from the end of the line lazily skip characters until the first _ is found, skip any following characters until encountering the second _ and stop right there.

It is easy to to find a similar block if we were looking for the very first one inside the string, but how about finding the last one?

Upvotes: 22

Views: 83290

Answers (2)

Toto
Toto

Reputation: 91415

Have a try with:

((?:_[^_\r\n]*){2})$

It matches an underscore followed by any number of any character that is not underscore or line break, all that occurs twice before the end of lien.

Upvotes: 11

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

The text between the second last _ and the end of the string should be matched

Use a negated character class, like

([^.]*$)

It will match everything from the end of the string that isn't ., resulting in the last quote (assuming each quote ends with a .)

http://regex101.com/r/fA3pI7/1

Upvotes: 24

Related Questions