#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2006
    Posts
    17
    Rep 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
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2007
    Posts
    765
    Rep Power
    929
    sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    159
    Rep Power
    208
    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.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2006
    Posts
    17
    Rep Power
    0
    Wow! Thanks for the help on this guys! Really appreciated.

    P



    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.

IMN logo majestic logo threadwatch logo seochat tools logo