The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages - More
> Regex Programming
|
Replace multiple characters with multiple characters
Discuss Replace multiple characters with multiple characters in the Regex Programming forum on Dev Shed. Replace multiple characters with multiple characters Regular expressions forum covering PCRE and POSIX techniques, practices, and standards. Regular expressions help shorten coding time by providing the ability to compact many lines of code into one string.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

May 22nd, 2009, 05:32 PM
|
|
Registered User
|
|
Join Date: Sep 2006
Posts: 17
Time spent in forums: 3 h 8 m 23 sec
Reputation Power: 0
|
|
|
Replace multiple characters with multiple characters
Hi,
I have various strings in a document of the type:
~,~
~,,,,,,~
~,,,~
And I need to replace them to get:
~x~
~xxxxxx~
~xxx~
The only criterion is that it only affects , characters that are between two ~
I've got (~)(,+)(~) to find all the comas I need.
I can get it to replace ~,~ with ~x~ but when there are multiple comas it only replacing with one ,
So ~,,,,,,~ becomes ~x~
Any idea how to get multiple replacements like this?
Many thanks,
Pat
|

May 22nd, 2009, 05:59 PM
|
|
|
|
__________________
sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);
|

May 24th, 2009, 10:00 AM
|
|
|
With tests:
Code:
#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use Test::More qw(no_plan);
#Replace all ',' in strings like ~,+~ with x
sub replace {
my $str=shift;
$str=~s/~(,+)~/'~'.('x' x length($1)).'~'/ge;
return $str;
}
is(replace('~,~'),'~x~');
is(replace('~,,,,~'),'~xxxx~');
is(replace('~~ ,'),'~~ ,');
You should be able to convert this to any language that supports callbacks in regexes.
|

May 24th, 2009, 03:27 PM
|
|
Registered User
|
|
Join Date: Sep 2006
Posts: 17
Time spent in forums: 3 h 8 m 23 sec
Reputation Power: 0
|
|
Wow! Thanks for the help on this guys! Really appreciated.
P
Quote: | Originally Posted by chorny_cpan With tests:
Code:
#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use Test::More qw(no_plan);
#Replace all ',' in strings like ~,+~ with x
sub replace {
my $str=shift;
$str=~s/~(,+)~/'~'.('x' x length($1)).'~'/ge;
return $str;
}
is(replace('~,~'),'~x~');
is(replace('~,,,,~'),'~xxxx~');
is(replace('~~ ,'),'~~ ,');
You should be able to convert this to any language that supports callbacks in regexes. |
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|