Regex: Split on uppercase

If you need to split a string based on uppercase values, for example “ComputeAsAService” in order to provide a readable string “Compute As A Service” you can do so simply by using regular expressions, in particular you can use the lookahead operator “?=”.

1
2
3
str = "ComputeAsAService"
parts = str.split(/(?=[A-Z])/)
>> ["Compute", "As", "A", "Service"]

Once you have all parts of the string, you can join them with a space, or simply deal with the array as you see fit.

1
2
3
str     = "ComputeAsAService"
parts   = str.split(/(?=[A-Z])/)
new_str = parts.join(' ')

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>