#!/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";