the_winter_mute
the_winter_mute

Reputation: 15

How to match the last occurrence of a pattern?

Given that I have the following string:

String 1 | string 2 | string 3

I want my regex to match the value after the last pipe and space, which in this case is "string 3".

Right now I am doing using this: /[^|]+$/i but it also return the space character after the pipe.

https://regex101.com/r/stnW0D/1

Upvotes: 1

Views: 217

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

str = "string 1 | string 2 | string 3"

str[/[^ |][^|]*\z/]
  #=> "string 3"

Upvotes: 0

steenslag
steenslag

Reputation: 80065

Without regex:

"String 1 | string 2 | string 3".split(" | ").last # => "string 3"

Upvotes: 1

Sebastián Palma
Sebastián Palma

Reputation: 33420

'String 1 | string 2 | string 3'[/(?<=\|\s)(\w+\s\d+\z)/]
# "string 3"

Where (escaped):

\|  # a pipe
\s  # a whitespace
\w+ # one or more of any word character
\s  # a whitespace
\d+ # one or more digits
\z  # end of string

(...)    # capture everything enclosed
(?<=...) # a positive lookbehind

Notice in this case the regex is already getting the last occurrence of the pattern in the string, by attaching it to the end of the string (\z). In other case you could use [\|\s]? instead of (\|\s) to match the string followed by a whitespace and a number and from there, access the last element in the returned array:

'String 1 | string 2 | string 3'.scan(/[\|\s]?(\w+\s\d+)/).last
# ["string 3"]

Upvotes: 0

Related Questions