Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Regex matching a string beginning with "root: " but not containing another string

by Eimi Metamorphoumai (Deacon)
on Sep 09, 2004 at 18:48 UTC ( [id://389835]=note: print w/replies, xml ) Need Help??


in reply to Regex matching a string beginning with "root: " but not containing another string

It can be done with just a standard regexp, but it's monumentally ugly. If you want to match "root:" not followed by "bar", you get
/root: #need root ($ #it could end there |([^b] #if not, first letter isn't b |b($|[^a] #or it can be b if it's not |a($|[^r]) #followed by ar /x
(Untested, I may have gotten it a little wrong.) Suffice to say, it's ugly, but it's doable. You just have to make sure that you always allow either the end of the string ($), any single character but the next, or the next character, as long as it itself isn't followed by (the rest of the string). Writing that for something long and complicated is a nightmare (unless someone has written a script to do it, which I don't know of).
  • Comment on Re: Regex matching a string beginning with "root: " but not containing another string
  • Download Code

Replies are listed 'Best First'.
Re^2: Regex matching a string beginning with "root: " but not containing another string
by jryan (Vicar) on Sep 09, 2004 at 20:08 UTC

    Here's a different way to do it. IMHO, the regex it produces will be much easier and make much more sense.

    use strict; my $email = "myself\@domain.of-my.own"; my $string = "root: myself\@domain.of-my.own"; my $re = inv_str_seq($email); $string =~ /^root: $re/ and print 1; sub inv_str_seq { my($string) = @_; my @c = map { quotemeta($_) } split '', $string; my $re = "\n [^$c[0]] \n"; $re .= " | " . join('',@c[0..$_-1]) . " [^$c[$_]]\n" for (1 .. $#c); $re = qr/$re/x; return qr/$re+ (?:[^$c[0]]|$)/x; }

    Update: Moved the quotemeta up.

Re^2: Regex matching a string beginning with "root: " but not containing another string
by Roy Johnson (Monsignor) on Sep 09, 2004 at 19:26 UTC
    Here's a little sub to generate such a regex from the string you want not to match:
    sub not_string_regex { my $str = shift; my $reg; for(0..length($str)-1) { my $let = substr($str,$_,1); $reg .= '($|[^'.$let.']|'.$let; } substr($reg, -2) = ''; $reg .= ')' x length($str); }

    Caution: Contents may have been coded under pressure.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://389835]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-26 03:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found