[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

removing spaces between single characters with regual expression

ciapecki

9/12/2006 5:50:00 PM

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

1 Answer

Paul Lutus

9/12/2006 6:05:00 PM

0

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.

--
Paul Lutus
http://www.ara...