Home: Perl Programming Help: Regular Expressions:
Regex mutiple match



gianni24
New User

Aug 30, 2017, 12:02 AM


Views: 7159
Regex mutiple match

Hi everybody,
thank you for your help!!
Let me go straight to the point: I need to run some regex that can match many times and extract all possible matches. Let me explain by one simple example


Code
$dict="        ABACUS        "; 
$regex=" ([A-Z ]*?)([AOU])([A-Z ]*?) ";
for(;$dict =~ m@$regex@g;){
print "($1)($2)($3)\n";
}
<>;


This one will print out:

( )(A)(BACUS)

but I need to find the other possible matches too:

( AB)(A)(CUS)
( ABAC)(U)(S)

How I can make it?


BillKSmith
Veteran

Aug 30, 2017, 6:49 AM


Views: 7153
Re: [gianni24] Regex mutiple match

I am not certain what you need. My best guess is that you want to ignore leading and trailing whitespace and then find all partitionings of the remaining string which match a pattern. This is definitely not a job for a single regex!

If you can clarify your requirements, I will look into possible solutions.

UPDATE:
Perhaps this is what you want.

Code
C:\Users\Bill\forums\guru>type gianni24.pl 
use strict;
use warnings;
my $dict = " ABACUS ";

for my $i (0..length($dict)-1) {
$dict =~ /
^
\s*
(\w{$i})
([AOU])
(\w*)
\s*
$
/x;
next if !defined $3;
print "($1)($2)($3)\n";
}


C:\Users\Bill\forums\guru>perl gianni24.pl
()(A)(BACUS)
(AB)(A)(CUS)
(ABAC)(U)(S)

Good Luck,
Bill

(This post was edited by BillKSmith on Aug 30, 2017, 7:31 AM)


gianni24
New User

Sep 1, 2017, 2:46 AM


Views: 7129
Re: [BillKSmith] Regex mutiple match

Thank you Bill: you marked the point, that's exactly what I needed.

Actually my regexes are a bit more complicated than the one I posted, but your solution applied with some minor modifications!

Thank you very much!