in reply to Converting BCBCBCBCBCCCB to (BC)^{5}CCB

If the case is that simple (your string could start by /^BC/ or by /^.*BC/), you can use the replacement operator s/// to get the right answer.
#!/usr/bin/perl -w use strict; my $source = "BCBCBCBCBCCCB"; my $group = "BC"; # the repeating string # capturing the left part, if any, # and removing it from the source my $left = substr($source,0, index($source,$group)); substr($source,0,index($source,$group)) =""; # counting the occurrence of the repeating group my $exp = $source =~ s/$group//g; #print the "formula" print "$left ($group)^{$exp}$source\n";
Output:
(BC)^{5}CCB
Changing source to "CCBCBCBCBCBCCCB";
You get the output:
CC (BC)^{5}CCB