Serhiy Boreyko Serhiy Boreyko - 5 days ago 6
Javascript Question

Regex, get some match from the end

I have text like this:


Some guy writes: some content.


or


Some guy said: some content.


and i want to get all content from 'writes' to the end.

It is looking simple:
(said | writes):. *


But. My text example can looks like this:


Some guy writes: blablabla, said: some content


Here i want to get only 'said: some content'.
But my regex geting all content from 'writes' to the end.
How to solve this problem?

Answer

Prepend the regex you have with ^.* and capture it:

^.*((?:said|writes):.*)

See the regex demo

The initial .* will grab the whole line (or string if DOTALL modifier is used) and will backtrack to accommodate for said: or writes: that are the last on the string/line.

The non-capturing group in (?:said|writes) is used for grouping only purposes, so that there is only one capturing group with ID = 1.

Details:

  • ^ - start of string/line anchor (depends on the modifiers used)
  • .* - any 0+ chars as many as possible (as * is a greedy quantifier) (other than line break symbols if DOTALL modifier is not used)
  • ((?:said|writes):.*) - Group 1 capturing:
    • (?:said|writes) - either said or writes char sequences
    • : - a colon
    • .* - any 0+ chars (other than line break symbols if DOTALL modifier is not used) up to the end of line/string.
Comments