Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert spaces into a string using Ruby [closed]

Tags:

string

regex

ruby

Insert spaces into a string using Ruby

Ex: I have "LoremIpsumDolorSitAmet", I want to get this "Lorem Ipsum Dolor Sit Amet"

like image 825
galata Avatar asked Sep 30 '12 07:09

galata


1 Answers

Assuming Ruby 1.9:

result = subject.split(/(?<=[a-z])(?=[A-Z])/)

This splits between a lowercase and an uppercase ASCII letter.

To insert spaces instead:

result = subject.gsub(/(?<=[a-z])(?=[A-Z])/, ' ')

See here:

irb(main):001:0> "LoremIpsumDolorSitAmet".gsub(/(?<=[a-z])(?=[A-Z])/, ' ')
=> "Lorem Ipsum Dolor Sit Amet"

If there can be single uppercase letters, you'd need to change your regex a bit:

irb(main):003:0* "ThisIsAString".gsub(/(?<=[A-Za-z])(?=[A-Z])/, ' ')
=> "This Is A String"
like image 72
Tim Pietzcker Avatar answered Oct 11 '22 07:10

Tim Pietzcker