Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression group repeated letters

Tags:

regex

ruby

repeat

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!

like image 803
misterwolf Avatar asked Oct 28 '17 11:10

misterwolf


People also ask

How do you determine if a string contains a sequence of repeated letters?

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.

How do you repeat a regular expression?

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.

How do you group together in regular expressions?

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.

Which regex matches one or more digits?

+: 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.


1 Answers

Just use another capturing group to catch the repeated characters.

s.scan(/((\w)\2*)/).map(&:first)
# => ["aaaaaaa", "bbbbbbbb", "c"]
like image 129
Avinash Raj Avatar answered Oct 13 '22 12:10

Avinash Raj