Insert spaces into a string using Ruby
Ex: I have "LoremIpsumDolorSitAmet"
, I want to get this "Lorem Ipsum Dolor Sit Amet"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With