Schnulli
Schnulli

Reputation: 41

Filtering matching patterns with regular expressions

I'm not very familiar with regular expressions in perl.
I want to filter names from a string e.g. "child mick jagger child john wayne child archimedes" between tags "child".

Result should be:

mick jagger

john wayne

archimedes

The number of names in the string is variable.

My perl program:

#!/usr/bin/perl

use strict 'vars';
use strict 'subs';
my ($x);
my $s="child mick jagger child john wayne child archimedes";

my @f=$s=~/(child.+(?!child))/igs;
foreach $x (@f)
{
    print "$x\n";
}; 

The program didn't work. Can anybody help?

Upvotes: 3

Views: 244

Answers (2)

Booboo
Booboo

Reputation: 44148

You can also do this with lookbehind:

?<=\bchild )(?:(?! child).)+

See Regex Demo

use strict;

my $s="child mick jagger child john wayne child archimedes";
my @f = $s =~/(?<=\bchild )(?:(?! child).)+/ig;
foreach my $x (@f) {
    print "$x\n";
};

Prints:

mick jagger
john wayne
archimedes

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163362

You might use:

\bchild \K(?:(?!child).)*(?!\S)
  • \bchild Match child preceded with a word boundary and followed by a space
  • \K Forget what was matched
  • (?:(?!child).)* Match any char except a newline not followed by child
  • (?!\S) Assert what is on the right is not a non whitespace char

Regex demo

Or use a non greedy dot variant

\bchild \K.+?(?= child|$)

Regex demo

Upvotes: 4

Related Questions