# Removing spaces between single characters with regual expres

**URL:** <https://www.ruby-forum.com/t/removing-spaces-between-single-characters-with-regual-expres/68442>\
**Category:** Ruby\
**Created:** [September 12, 2006, 7:55pm UTC](https://www.ruby-forum.com/t/removing-spaces-between-single-characters-with-regual-expres/68442 "2006-09-12T19:55:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ciapecki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/9fc29f/32.png) [@ciapecki](https://www.ruby-forum.com/u/ciapecki)\
**Post date:** [September 12, 2006, 7:55pm UTC](https://www.ruby-forum.com/t/removing-spaces-between-single-characters-with-regual-expres/68442/1 "2006-09-12T19:55:36Z")

</div>

I want to remove the spaces in the string only then when they stand  
between 2 single characters.  
for example: O J Simpson should be translated into OJ Simpson  
‘A B C’ -\> ‘ABC’  
‘AB C’ -\> ‘AB C’ (no change)  
‘Teddy Bear A B’ -\> ‘Teddy Bear AB’

how can I do that with regular expression?  
Thanks for your help  
chris

---

<div class="post-metadata">

**Author:** ![ciapecki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/9fc29f/32.png) [@ciapecki](https://www.ruby-forum.com/u/ciapecki)\
**Post date:** [September 12, 2006, 8:07pm UTC](https://www.ruby-forum.com/t/removing-spaces-between-single-characters-with-regual-expres/68442/2 "2006-09-12T20:07:38Z")

</div>

ciapecki wrote:

> I want to remove the spaces in the string only then when they stand  
> between 2 single characters.  
> for example: O J Simpson should be translated into OJ Simpson  
> ‘A B C’ -\> ‘ABC’

This conversion doesn’t follow from your expressed rule. It is, not two,  
but  
three, single characters separated by spaces.

> ‘AB C’ -\> ‘AB C’ (no change)

This is why your example of ‘A B C’ -\> ‘ABC’ doesn’t actually follow  
from  
your request. The first step is to convert ‘A B C’ -\> ‘AB C’, then the  
next  
conversion won’t happen because the string is no longer two single  
characters separated by a space.

> ‘Teddy Bear A B’ -\> ‘Teddy Bear AB’
> 
> how can I do that with regular expression?

* * *

#!/usr/bin/ruby

data=\<\<EOF  
abc def a b c d e f g ab cd efgh ijkl  
EOF

puts data

data.gsub!(/(\b\w) (\w\b)/,"\1\2")

puts data

* * *

Output:

abc def a b c d e f g ab cd efgh ijkl  
abc def ab cd ef g ab cd efgh ijkl

Notice how the ‘g’ was left an orphan, for the reason explained above.
