从特定单词之前的字符串中删除所有内容?

时间:2013-08-14 16:18:14

标签: ruby

如何在特定单词(或包括第一个空格和后面)之前删除字符串中的所有内容?

我有一个这样的字符串:

12345 Delivered to: Joe Schmoe

我只想要Delivered to: Joe Schmoe

所以,基本上来自第一个空格和后面的任何东西都不想

我正在运行Ruby 1.9.3。

3 个答案:

答案 0 :(得分:3)

使用正则表达式只选择所需字符串的一部分。

"12345 Delivered to: Joe Schmoe"[/Delive.*/]
# => "Delivered to: Joe Schmoe"

答案 1 :(得分:0)

有几种不同的方式是可能的。这是一对夫妇:

s = '12345 Delivered to: Joe Schmoe'
s.split(' ')[1..-1].join(' ') # split on spaces, take the last parts, join on space
# or
s[s.index(' ')+1..-1] # Find the index of the first space and just take the rest
# or
/.*?\s(.*)/.match(s)[1] # Use a reg ex to pick out the bits after the first space

答案 2 :(得分:0)

如果Delivered并不总是第二个单词,您可以这样使用:

s_line = "12345 Delivered to: Joe Schmoe"
puts s_line[/\s.*/].strip #=> "Delivered to: Joe Schmoe"
相关问题