Ruby:仅从字符串中删除前导和尾随子字符串

时间:2014-09-18 07:05:14

标签: ruby ruby-on-rails-3

我想从字符串中删除一些子字符串,但该子字符串应该只是前面或后面的。

Example :- Hotel Silver Stone Residency
String to be removed :- Residency
Output :- Hotel Silver Stone 

Example :- Hotel Silver Residency Stone 
String to be removed :- Residency
Output :- Hotel Silver Residency Stone

2 个答案:

答案 0 :(得分:2)

sub_str = "Residency"
s = "Residency Hotel Residency Silver Stone Residency"
s.gsub(/^#{sub_str}|#{sub_str}$/,'').strip
=> "Hotel Residency Silver Stone"

答案 1 :(得分:0)

你可以使用regexp来做,但由于我不是正则表达式专家,我可以告诉你如何使用split / join

s="Hotel Silver Stone Residency String"
string_to_be_removed="Residency"

tokens=s.split(' ')
tokens.shift if tokens.first==string_to_be_removed
tokens.pop if tokens.last==string_to_be_removed
s=tokens.join(' ')