Jassi
Jassi

Reputation: 541

Substitute same number of repeated characters with others using Regex

I want to replace the repeating characters with other character for the same amount of repeated character and if it is repeating at the start of the string. Minimum repeating number should be more than 2.

For ex: $string = 'bbbbabcdeeeeee' Here bbbb should be replaced with yyyy

But if $string = 'bbcccccccddddddeeeffdfg' should not replace anything as first repeating character is not more than two times

$string =~ s/^(b){3,}/y/ would replace only more than 2 b to only one y

Is it possible to substitute using one line regular expression? Note: It would be nice if someone would respond in Perl or Python.

Upvotes: 2

Views: 2498

Answers (4)

anubhava
anubhava

Reputation: 785156

You can use code like this:

$string='bbbbcccccccddddddeeeffdfg';
$string =~ s/^((\w)\2{2,})/'y' x length($1)/e;
print $string. "\n";

OUTPUT

yyyycccccccddddddeeeffdfg
  • /e -> To execute code in replacement
  • 'y' x length($1) -> To repeat character 'y' as many times as the length of matched group #1

Upvotes: 3

Toto
Toto

Reputation: 91415

How about:

my $re = qr~^((.)\2{2,})~;
while(<DATA>) {
    chomp;
    s:$re:'y' x length($1):e;
    say;
}


__DATA__
bbbbabcdeeeeee
bbcccccccddddddeeeffdfg
xxxxxx

output:

yyyyabcdeeeeee
bbcccccccddddddeeeffdfg
yyyyyy

Upvotes: 2

user3322306
user3322306

Reputation: 1

If you want to replace just a specific character, then in bash (using sed) you can use the following:

# echo aabcddd | sed '/\(a\)\{3,\}/{s/a/y/g}'
aabcddd
# echo aaabcddd | sed '/\(a\)\{3,\}/{s/a/y/g}'
yyybcddd

Upvotes: -1

markcial
markcial

Reputation: 9323

I don't know in which language you wan't this, but i will make a php script sample and you can convert it to your language of choice:

php > echo preg_replace('/([^b])b{3}([^b])/','$1yyy$2','aaabbbccc');
aaayyyccc
php > echo preg_replace('/([^b])b{3}([^b])/','$1yyy$2','aaaabbbbcccc');
aaaabbbbcccc

EDIT

If you want to only match beginning chars use tick char:

php > echo preg_replace('/^b{3}([^b])/','yyy$2','aaaabbbbcccc');
aaaabbbbcccc
php > echo preg_replace('/^b{3}([^b])/','yyy$2','bbbbcccc');
bbbbcccc
php > echo preg_replace('/^b{3}([^b])/','yyy$2','bbbcccc');
yyyccc
php > echo preg_replace('/^b{3}([^b])/','yyy$2','bbcccc');
bbcccc

perl version :

#/usr/bin/perl
$string = 'bbbccc';
$string =~ s/^b{3}([^b])/yyy$1/;
print $string;
$string = 'bbcc';
$string =~ s/^b{3}([^b])/yyy$1/;
print $string;
$string = 'bbbbcccc';
$string =~ s/^b{3}([^b])/yyy$1/;
print $string;

Upvotes: 0

Related Questions