Ruby 将字符串中的所有内容放在特定单词之前?
如何删除特定单词前字符串中的所有内容(或包括第一个空格和后面) 我有这样一个字符串:Ruby 将字符串中的所有内容放在特定单词之前?,ruby,Ruby,如何删除特定单词前字符串中的所有内容(或包括第一个空格和后面) 我有这样一个字符串: 12345 Delivered to: Joe Schmoe 我只想发送给:Joe Schmoe 所以,基本上从第一个空间到后面的任何东西我都不想要 我正在运行Ruby 1.9.3。使用正则表达式只选择所需字符串的一部分 "12345 Delivered to: Joe Schmoe"[/Delive.*/] # => "Delivered to: Joe Schmoe" 使用正则表达式仅选择所需字符
12345 Delivered to: Joe Schmoe
我只想发送给:Joe Schmoe
所以,基本上从第一个空间到后面的任何东西我都不想要
我正在运行Ruby 1.9.3。使用正则表达式只选择所需字符串的一部分
"12345 Delivered to: Joe Schmoe"[/Delive.*/]
# => "Delivered to: Joe Schmoe"
使用正则表达式仅选择所需字符串的一部分
"12345 Delivered to: Joe Schmoe"[/Delive.*/]
# => "Delivered to: Joe Schmoe"
有很多不同的方法是可能的。以下是几点:
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
有很多不同的方法是可能的。以下是几点:
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
如果交付并不总是第二个词,您可以这样使用:
s_line = "12345 Delivered to: Joe Schmoe"
puts s_line[/\s.*/].strip #=> "Delivered to: Joe Schmoe"
如果交付并不总是第二个词,您可以这样使用:
s_line = "12345 Delivered to: Joe Schmoe"
puts s_line[/\s.*/].strip #=> "Delivered to: Joe Schmoe"