fabersky fabersky - 1 month ago 6
Ruby Question

Split string on capital letters, but not if preceded by whitespace

I have a string that looks like


"AaaBbbCcc DddEee"


I'm splitting it with

my_string.scan(/[A-Z][a-z]+/)


and the result is


["Aaa", "Bbb", "Ccc", "Ddd", "Eee"]


What I'd like to achieve is to not split the string if the capital letter is preceded by a white space, so the result would look like


["Aaa", "Bbb", "Ccc Ddd", "Eee"]

ndn ndn
Answer
my_string.split(/(?<!\s)(?=[A-Z])/)

This matches positions that are not preceded by a whitespace (negative lookbehind - (?<!\s)) and are followed by a capital letter (positive lookahead - (?=[A-Z])).