Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi

I want a regex that can match this:

# Need To match: # Hello One World # Hello World # HelloWorld # Hello One Two World # Hello Two Three World # Hello One Three World #Regex I Tried sub Filter { my $Text = shift; if ($Text=~m/Hello(one|two|three| )*World/g) { return 1; }else{ return 0; } }

Any help ?

Replies are listed 'Best First'.
Re: Regex Problem
by jwkrahn (Abbot) on Apr 11, 2010 at 16:15 UTC
    sub Filter { my $Text = shift; return $Text =~ /Hello(?i:one|two|three| )*World/ ? 1 : 0; }

    Or:

    sub Filter { my $Text = shift; return 0 + $Text =~ /Hello(?i:one|two|three| )*World/; }

    Or just:

    sub Filter { my $Text = shift; return $Text =~ /Hello(?i:one|two|three| )*World/; }
Re: Regex Problem
by ww (Archbishop) on Apr 11, 2010 at 15:58 UTC
    Sure:
    • perlretut
    • Tutorials (see:Pattern-Matching-Regular-Expressions-and-Parsing]
    • Your textbook...

    Hints: check carefully for discussions of "capturing," $n variables, and (additional) modifiers (if those other than /g).

Re: Regex Problem
by Gangabass (Vicar) on Apr 11, 2010 at 15:55 UTC
    $Text =~ m/Hello(one|two|three| )*World/ig;
Re: Regex Problem
by choroba (Cardinal) on Apr 11, 2010 at 21:34 UTC
    /^(?:Hello One World|Hello World|HelloWorld|Hello One Two World|Hello +Two Three World|Hello One Three World)$/
    No, that was a joke ;)

    If the ordering of One, Two, and Three is important, you could use something like

    /Hello(?: One)?(?: Two)?(?: Three)? ?World/
Re: Regex Problem
by JavaFan (Canon) on Apr 12, 2010 at 09:23 UTC
    I want a regex that can match this:

    It's not very useful to give a few examples of what the regex should match. /./ will match them. So will /^(Hello One World|Hello World|HelloWorld|Hello One Two World|Hello Two Three World|Hello One Three World)$/. You probably need something in between those extremes, but it's impossible to determine from your problem description where that something is. You should at least give some indication of what strings shouldn't be matched.