Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering matching patterns with regular expressions

Tags:

regex

filter

perl

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?

like image 513
Schnulli Avatar asked Jun 09 '26 05:06

Schnulli


1 Answers

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

like image 197
The fourth bird Avatar answered Jun 11 '26 20:06

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!