From: Pit Capitain Date: 2006-04-06T22:36:52+09:00 Subject: Re: String generalization Peter Szinek schrieb: > Hello all, > > I am having the following problem: I have to implement a method > which accepts a string and returns a generalized form of the string. > Some examples: > > '12345' -> \d+ > 'ABCDE' -> [A-Z]+ > 'john.smith@my.super.server.rb' -> [a-z]+\.[a-z]+@([a-z]+\.)+[a-z] > '123-45-678-90' -> (\d+-)+\d+ > 'item:' -> [a-z]+: > 'Peter, SZINEK': -> [A-Z][a-z]+, [A-Z]+ > 'http://www.google.com' -> [a-z]+://([a-z]+\.)+[a-z] > 'jd�;d:L348kddd3' -> .* Peter, thanks for the quiz. I needed it right now :-) I'm not sure I understand the rules. I had expected: '//' -> /+ 'jd�;d:L348kddd3' -> [a-z]+�;[a-z]:[A-Z]\d+[a-z]+\d Anyway, here's a first implementation for the use cases you've shown: def generalize( str ) str.gsub( /\d+|[a-z]+|[A-Z]+|\./ ) do |match| case match when /\d{2,}/: "\\d+" when /\d/: "\\d" when /[a-z]{2,}/: "[a-z]+" when /[a-z]/: "[a-z]" when /[A-Z]{2,}/: "[A-Z]+" when /[A-Z]/: "[A-Z]" when /\./: "\\." end end.gsub( /(.+)\1+/, "(\\1)+" ) end You notice some repetitions, so you can generalize it further. It isn't perfect, but maybe gets you going. Regards, Pit