How do I divide a camel case string in Ruby? -


i'm using ruby 2.4. want create new string camel-case string inserting spaces before capital letters. if have

abcdef 

i want result of

abc def 

whereas if have string of just

abcdef 

then nothing should happen. string of

abcdefg 

should result as

abc defg 

i tried below

  def format_camel_case_str(str)     if str.present? && str.length > 1 &&        str !~ /[[:space:]]/ && !str.upcase.eql?(str) && str[0].upcase.eql?(str[0]) && str[1..str.length] =~ /[a-z]/       str = "#{str[0..(str.index(/[a-z]/) - 1)]} #{str[str.index(/[a-z]/)..str.length]}"     end     str   end 

but returns input twice. also, should consider case of string "aaabbbccc" (should "aaa bbb ccc").

this 1 little bit harder read, since it's regex, example cases can done with:

gsub(/(?<!\a)(?<char>[a-z])(?=[a-z])/, ' \k<char>')  ['abcdef', 'abcdef', 'abcdefg', 'aaabbbccc'].each |str|   puts "#{str} => #{str.gsub(/(?<!\a)(?<char>[a-z])(?=[a-z])/, ' \k<char>')}" end # abcdef => abc def # abcdef => abcdef # abcdefg => abc defg # aaabbbccc => aaa bbb ccc 

regex explanation: (?<!\a) negative lookbehind, ensuring previous character not start of string. (?<char>[a-z]) matches , captures uppercase character match group named 'char'. (?=[a-z]) positive lookahead make sure next character lowercase.

so, because of positive lookahead, you'll match uppercase character comes before lowercase character, , negative lookbehind ensures uppercase not @ start of string.

the second parameter gsub replacement string, space followed whatever captured match group 'char'


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -