0

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 letter is e " --> "the fifth letter is"

1
  • I don't get your example. Which one is A and B here? Are there restrictions? like the string being surrounded by more than one space? In your example e is not between two spaces. What is the replacement? removing it? Commented Oct 10, 2011 at 19:25

3 Answers 3

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 

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, it is wrong because the question is constantly being changed, so I should be constantly updating the answer...
2

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.

Comments

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

1 Comment

It works for me. Of course, I've edited the post a few times in between.... (Standard FGitW technique, y'know? ;-))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.