I am trying to group all the repeated letters in a string.
Eg:
"aaaaaaabbbbbbbbc" => [['aaaaaaa'],['bbbbbbbb'],['c']]
Using logic and Ruby, the only way I could find to reach my intention was:
.scan(/(?:a+|A+)|(?:b+|B+)|(?:c+|C+)| ..... (?:y+|Y+)|(?:z+|Z+))
where ...
are the other alphabet letters.
There is a way to Dry that RegEx?
I used backtrace (\1)
too, but it doesn't match the single words and it doesn't return me the exact letters match => (\w+)\1
=> [['aa'],['bb']]
Uhm, am I wrong to use the regular expressions for this case and I should use Ruby methods with iterations?
I will glad to hear your opinion :) Thanks!
push(char[i]); } else { tempArry[char[i]] = []; tempArry[char[i]]. push(char[i]); } } console. log(tempArry); This will even return the number of repeated characters also.
An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once. An expression followed by '? ' may be repeated zero or one times only.
By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.
+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
Just use another capturing group to catch the repeated characters.
s.scan(/((\w)\2*)/).map(&:first)
# => ["aaaaaaa", "bbbbbbbb", "c"]
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