Reputation: 6815
I have a number of possible patterns for title which I want to capture using Ruby regexp.
How do I put this into one regexp pattern?
This method deals with the 2nd case only:
def self.format_title(title)
title.match(/(?:.+)\|(.+)/).to_a.first.strip
end
Upvotes: 2
Views: 587
Reputation: 35084
Your code can be rewritten into: title[/\|(.+)/),1].strip
And for all four cases I recommend to use gsub
:
def format_title title
title.gsub(/.+[\|\/]/,'').gsub(/^\[.+\]/,'').strip
end
Upvotes: 1
Reputation: 655269
Try this regular expression:
/^(?:[^|]*\||[^\/]*\/|\[[^\]]*\])?(.+)/
The optional non-capturing group (?:[^|]*\||[^\/]*\/|\[[^\]]*\])
consists of a pattern for each case:
[^|]*\|
matches everything up to the first |
,[^\/]*\/
matches everything up to the first /
, and \[[^\]]*\]
matches everything between [
and the first following ]
at the begin of the stringUpvotes: 1