I have a nice CamelCase string such as ImageWideNice or ImageNarrowUgly. Now I want to break that string in its substrings, such as Image, Wide or Narrow, and Nice or Ugly.
I thought this could be solved simply by
camelCaseString =~ /(Image)((Wide)|(Narrow))((Nice)|(Ugly))/ But strangely, this will only fill $1 and $2, but not $3.
Do you have a better idea for splitting that string?
split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.
The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.
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].
I know this is old, but worth mentioning for others who might be looking for this. In rails you could do this: "NowIsTheTime".underscore.humanize
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