CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
replacement with exact number of chars

 



Anglachel
Novice

Dec 3, 2010, 8:29 AM

Post #1 of 4 (4862 views)
replacement with exact number of chars Can't Post

Sorry for basic question. How I can replace some pattern with the exact number of characters?
Let's say I have a string AAAABBBBCCCC and variables that keep start and end positions of B (characters defined here with B in real world could be any, I just know only position of pattern I want to replace not pattern itself). And I want to replace this pattern with the same number (known for me) of X characters.
So I use

Code
my $range = $end-$start; 
$string =~ s/^(.{$start})(.{$range})(.*)$/$1?{$range}$3/;

What should I use on the place of question mark?
Now I'm using rather awkward construction:

Code
for (my $j=0; $j<$range; $j++) { 
$x .= "X"; }

(the $x plays instead of question mark in my expression)
Any help would be appreciated!


(This post was edited by Anglachel on Dec 3, 2010, 8:30 AM)


Zhris
User

Dec 5, 2010, 1:34 PM

Post #2 of 4 (4685 views)
Re: [Anglachel] replacement with exact number of chars [In reply to] Can't Post

I think it would be best if you used the substr function instead of a regular expression:


Code
#!/usr/bin/perl 
use strict;
use warnings;

my $string = 'AAAABBBBCCCC';
print "$string\n";

my $replace_char = 'X';
my $replace_start = "4";
my $replace_end = "8";

my $replace_range = $replace_end - $replace_start;

my $replace_string;
for (1 .. $replace_range) {
$replace_string .= $replace_char;
}

substr ($string, $replace_start, $replace_range) = $replace_string;
print "$string\n";


Chris


(This post was edited by Zhris on Dec 5, 2010, 1:37 PM)


rovf
Veteran

Dec 6, 2010, 2:05 AM

Post #3 of 4 (4622 views)
Re: [Anglachel] replacement with exact number of chars [In reply to] Can't Post


Code
substr($s,$p,$m) = $t x $n


replaces the $m characters in string $s, starting at position $p, by $n occurences of string $t.


Code
$s =~ tr/B/X/


replaces in string $s all occurances of the letter B by the letter X.


Anglachel
Novice

Dec 8, 2010, 8:58 AM

Post #4 of 4 (4442 views)
Re: [Anglachel] replacement with exact number of chars [In reply to] Can't Post

Thank you for help! I was also driven to use substr due to the problem of the quantifier limit 32766 in regex.Smile

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives