Find the answer to your Linux question:
Results 1 to 2 of 2
I was wondering how to write this regular expression differently: $line !~ /this that( now| other)/ Here is the catch, I have to use "=~" instead of "!~". Is there ...
  1. #1
    Just Joined!
    Join Date
    Apr 2009
    Posts
    1

    Regular Expression Help

    I was wondering how to write this regular expression differently:

    $line !~ /this that( now| other)/

    Here is the catch, I have to use "=~" instead of "!~". Is there a way of doing this? I can't seem to figure it out. What's happening is I'm passing this pattern into a method where the =~ is hardcoded, but I want to match a phrase with a certain prefix ("this that" in this case) but not if it has certain suffixes (" now" or " other" in my above example). I can't seem to figure this out. Thanks!

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    For what it's worth, the expression you have given does not do what you want. The line:
    Code:
    $line !~ /this that( now| other)/
    would return true for the string "hello", even though this obviously does not have the "this that" prefix.

    What I think you really want is a slightly more advanced Perl feature: negative lookaheads. You can't really match the complement of a string with regular expressions, but you can require that a certain something does not follow the pattern.

    Suppose we want a regular expression that matches a string beginning with "this that" and followed by anything not "now" or "other". We would use the following:
    Code:
    /^this that(?! now| other)/
    (?!PATTERN) means that whatever comes after the match does not match this pattern. The match will only include the "this that" portion, but the lookahead assertion will hold.

    For some more details on lookaheads and lookbehinds, try this:
    perlre - Perl regular expressions

    Hope that helps.
    DISTRO=Arch
    Registered Linux User #388732

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...