How to split a CamelCase string in its substrings in Ruby?

s="nowIsTheTime"

s.split /(?=[A-Z])/

=> ["now", "Is", "The", "Time"]

?=pattern is an example of positive lookahead. It essentially matches a point in the string right before pattern. It doesn’t consume the characters, that is, it doesn’t include pattern as part of the match. Another example:

    irb> 'streets'.sub /t(?=s)/, '-'
=> "stree-s"

In this case the s is matched (only the second t matches) but not replaced. Thanks to @Bryce and his regexp doc link. Bryce Anderson adds an explanation:

The?=at the beginning of the()match group is called positive
lookahead,
which is just a way of saying that while the regex is
looking at the characters in determining whether it matches, it’s not
making them part of the match. split()normally eats the in-between
characters, but in this case the match itself is empty, so there’s
nothing [there].

Leave a Comment