在某些单词出现时截断字符串

时间:2014-10-24 06:05:26

标签: ruby

如何在某个单词出现时截断字符串?

例如,我收到了字符串:

a = "Is your question about programming? <--truncate--> We prefer questions that can be answered, not just discussed." 

我只想输出&#34;您对编程有疑问吗?&#34;

4 个答案:

答案 0 :(得分:1)

你可以创建一个匹配关键字的正则表达式,然后创建一切,直到字符串结束,然后将sub替换应用于替换匹配的字符串:

string = "Is your question about programming? <--truncate-->\nWe prefer questions that can be answered, not just discussed."

keyword = '<--truncate-->'
regex = /#{Regexp.escape keyword}.*\z/m

string.sub(regex, '')
#=> "Is your question about programming? "

我确保它也适用于多行字符串。您可能希望在最后添加.strip以删除前导和尾随空格:

string.sub(regex, '').strip
#=> "Is your question about programming?"

答案 1 :(得分:0)

a.split('<--truncate-->').first.strip

或者用正则表达式分开

a.split(/\s*<--truncate-->/).first

答案 2 :(得分:0)

由于最多似乎有一个分隔符(如WordPress中的<!--more-->),我使用String#partition

a = "Is your question about programming? <--truncate--> We prefer questions that can be answered, not just discussed." 

excerpt, separator, more = a.partition('<--truncate-->')

excerpt    #=> "Is your question about programming? "
separator  #=> "<--truncate-->"
more       #=> " We prefer questions that can be answered, not just discussed."

答案 3 :(得分:-1)

您可以使用范围切片字符串。索引截断以指示切片的结束。

a[0...a.index("<--truncate-->")]
# => "Is your question about programming?"

你可以用正则表达式完成同样的事情:

a.match(/(.*)<--truncate-->/).captures.first
# => "Is your question about programming?"