Reputation: 41
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
Reputation: 44148
You can also do this with lookbehind:
?<=\bchild )(?:(?! child).)+
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
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 charOr use a non greedy dot variant
\bchild \K.+?(?= child|$)
Upvotes: 4