Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: Replacing a specfied instance of a pattern in a string

by krisahoch (Deacon)
on Jul 14, 2005 at 21:35 UTC ( #475056=note: print w/ replies, xml ) Need Help??


in reply to Re: Replacing a specfied instance of a pattern in a string
in thread Replacing a specfied instance of a pattern in a string

Now, is there a way to do it with Regular Expression?


Comment on Re^2: Replacing a specfied instance of a pattern in a string
Re^3: Replacing a specfied instance of a pattern in a string
by ikegami (Pope) on Jul 14, 2005 at 21:36 UTC
    my $str = 'Fsih my test variable is fsihd or is it gfsih or gfsih +d fsih'; # 1111 2222 3333 + 4444 my $substr = 'fsih'; my $regexp = qr/\Q$substr\E/; my $replace = 'fish'; my $instance = 3; # 3rd print("$str\n"); my $pre_count = $instance - 1; $str =~ s/((?:$regexp.*?){$pre_count})$regexp/$1$replace/; print("$str\n");

    You might have noticed both of these are case sensitive. Both can be made case-insensitive. The non-regexp version is most likely much faster. The regexp version can handle regexps instead of constant strings.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://475056]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (12)
As of 2015-07-03 16:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (54 votes), past polls