我有许多可能的标题模式,我想使用 Ruby regexp 捕获这些模式。
- 只是标题
- 忽略 |要捕获的标题
- 忽略/要捕获的标题
- [忽略]要捕获的标题
如何将其放入一个正则表达式模式中?
这个方法只处理第二种情况:
def self.format_title(title)
title.match(/(?:.+)\|(.+)/).to_a.first.strip
end
最佳答案
你的代码可以改写成:title[/\|(.+)/),1].strip
对于所有四种情况,我建议使用 gsub
:
def format_title title
title.gsub(/.+[\|\/]/,'').gsub(/^\[.+\]/,'').strip
end
关于 ruby 正则表达式 : complex pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4773531/