Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

wanting a more explicit regex

by wolfger (Deacon)
on Feb 12, 2008 at 13:43 UTC ( #667555=perlquestion: print w/replies, xml ) Need Help??

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

I whipped up a quick regex today to satisfy a range of possible domain names, and while it matches everything I want, it also matches a few things I don't want. Easy enough to error-proof with an "if", but I'm wondering if there's a way to wrap this all up in one regex. Here's what I have:


The only problem is in the xyz11? part of the expression. I want to match xyz, xy1, and xyz1, but not xy11, and I couldn't figure out how to limit that.

Replies are listed 'Best First'.
Re: wanting a more explicit regex
by moritz (Cardinal) on Feb 12, 2008 at 13:47 UTC
    You can use an alternation: xy(?:z|1|z1)

    If the list of possible alternations grows too large to list them explicitly, you have to tell us a bit more about your problem, perhaps there's a better, generic solution.

Re: wanting a more explicit regex
by poolpi (Hermit) on Feb 12, 2008 at 14:12 UTC
    #!/usr/bin/perl use strict; use warnings; my @url = ( '', 'c3.xy1', 'b1.xyz1', 'a3.xy11'); for (@url){ $_ .= '.nota.url'; / [a-c][1-3] [.] xy (:? z[1]? | 1 ) [.] nota [.] url /xms ? print "$_ : OK\n" : print "$_ : NOK\n"; }
    Output: : OK c3.xy1.nota.url : OK b1.xyz1.nota.url : OK a3.xy11.nota.url : NOK


    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb
Re: wanting a more explicit regex
by Anonymous Monk on Feb 12, 2008 at 14:21 UTC
    use Regex::PreSuf; my $re = presuf(qw( abc1 abc2 abc3 xyz1 xyz xy1 nota url )); print "$re\n"; __END__ (?:abc[123]|nota|url|xy(?:z1|[1z]))

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://667555]
Approved by citromatik
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2021-02-26 16:41 GMT
Find Nodes?
    Voting Booth?

    No recent polls found