Thibault Falise
Thibault Falise

Reputation: 5885

Regex - Replace when group contains multiple captures

I am having trouble trying to get some replaces working with my regex.

Here is some sample data I'm working with :

$/Data:
$One
$Two

$/New:
$Four
$Five

Here is the result I'd like to obtain :

$/Data/One
$/Data/Two
$/New/Four
$/New/Five

Currently, I'm using this regex :

(\$/.*?):\r\n(?:(?:\$(.*)\r\n)*)+

This allows me to capture this data

\1 => $/Data
\2 => One
      Two

... same for other group

Is there a way to get the desired result with a regex ? Currently, when I use a \1/\2 replace, I only get the replace for the last item of the \2 capture group.

Upvotes: 0

Views: 181

Answers (2)

Toto
Toto

Reputation: 91373

As you don't say wich language, here is a perl script that do the job:

#!/usr/bin/perl 
use 5.10.1;
use warnings;
use strict;
use Data::Dumper;

my $str = '$/Data:
$One
$Two

$/New:
$Four
$Five';

my @l = split/\r?\n/, $str;
my @arr;
my $res;
for(@l) {
  chomp;
  if (m!^(\$/.*?):!) {
    $res = $1;
  } elsif (m!^\$(.+)$!) {
    push @arr, $res.'/'.$1;
  } elsif( m!^$!) {
    $res = '';
  }
}
say Dumper \@arr;

Output:

$VAR1 = [
          '$/Data/One',
          '$/Data/Two',
          '$/New/Four',
          '$/New/Five'
        ];

Upvotes: 1

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

Perl? I'd be inclined to do this one in a loop, find the $/: lines, extract whatever then splice that into all following lines until another $/: line

Upvotes: 1

Related Questions