fabersky fabersky - 1 year ago 58
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


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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download