开发者

regex: replace string if it's between two spaces, leave unchanged if not

开发者 https://www.devze.com 2023-04-12 14:36 出处:网络
I need to remove a string A that exists in another string B only if string A is between two spaces. string A = \"e\"

I need to remove a string A that exists in another string B only if string A is between two spaces.

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

Example for replacing 'e' : "the fifth le开发者_StackOverflow中文版tter is e " --> "the fifth letter is"


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 

Edited the answer after you edited the question. A possible regular expression to find an "e" character between two space characters is /\se\s/. In this case I'm replacing it with an empty string "". You can use gsub which returns a copy of the string or gsub! to modify the original string.

UPDATE: Since you edited the question again, here's un updated answer:

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 


You don't really need regex for this.

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

PS. In Ruby it's a constant if it begins with an uppercase letter. DS.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号