From: Rob Biedenharn Date: 2008-11-13T21:10:32+09:00 Subject: Re: Regular expression for matching spaced letters needed On Nov 13, 2008, at 6:14 AM, Peter Szinek wrote: >>> please tell me, if this isn't the right place to ask. >>> I am looking for a regular expression which matches "spaced words" >>> in a sentence like, for example, "M I L L E R" or "B u s h" and >>> replaces them with "Miller" or "Bush". >>> I found out that sub!(/\s?([A-Z])\s([A-Z])\s([A-Z])\s([A-Z])\s([A- >>> Z])\s?/,' \1\2\3\4\5 ') works for 4 Letters. (Analogue for any >>> other fix number.) But I just can't figure out how to match any >>> number and how to don't match any letters of surrounding words. >>> "A B C D E" -> "ABCDE" >>> "a b c d" -> "abcd" >>> "hello A B C test" -> "hello ABC test" >>> Think you got it. Which regexp will do the job? >>> Regards Jan > > The regexp version I came up with: > > >> "A B C D E F G".scan(/\s?([A-Z])/).flatten.join('') > => "ABCDEFG" > > Cheers, > Peter > ___ > http://www.rubyrailways.com > Well, not a regexp by itself, but this seems to work: irb> strings = ["A B C D E", "a b c d e", "hello A B C world"] => ["A B C D E", "a b c d e", "hello A B C world"] irb> strings.map {|input| input.gsub(/\b(?:\w\s)+\w\b/) {|m| m.gsub(/ \s/, '')} } => ["ABCDE", "abcde", "hello ABC world"] -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com