正则表达式:如果它在两个空格之间,则替换字符串,否则保持不变

时间:2011-10-10 19:17:41

标签: ruby regex

只有当字符串A在两个空格之间时,我才需要删除存在于另一个字符串B中的字符串A.

string A = "e"
string B = "the fifth letter is e "

替换'e'的示例:"the fifth letter is e " - > "the fifth letter is"

3 个答案:

答案 0 :(得分:3)

ruby-1.9.2-p290 :006 > a = "the fifth letter is e "
 => "the fifth letter is e " 
ruby-1.9.2-p290 :007 > print a.gsub(/\se\s/,"")
the fifth letter is => nil 

编辑问题后编辑了答案。用于在两个空格字符之间找到“e”字符的可能正则表达式是/\se\s/。在这种情况下,我用空字符串""替换它。您可以使用gsub返回字符串副本或gsub!来修改原始字符串。

更新:由于您再次编辑了问题,这里是未更新的答案:

ruby-1.9.2-p290 :001 > a = "e"
 => "e" 
ruby-1.9.2-p290 :002 > b = "the fifth letter is e "
 => "the fifth letter is e " 
ruby-1.9.2-p290 :003 > print b.gsub(/\s#{a}\s/,"")
the fifth letter is => nil 

答案 1 :(得分:2)

你真的不需要正则表达式。

a = "e"
b = "the fifth letter is e "
c = b.gsub(" " << a << " ", "")

PS。在Ruby中,如果它以大写字母开头,则它是常量。 DS。

答案 2 :(得分:0)

str = 'the fifth letter is e'
thing = 'e'
str.sub! /\s+#{thing}\s+/, ''