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 ...
- 04-16-2009 #1Just 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!
- 04-17-2009 #2
For what it's worth, the expression you have given does not do what you want. The line:
would return true for the string "hello", even though this obviously does not have the "this that" prefix.Code:$line !~ /this that( now| other)/
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:
(?!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.Code:/^this that(?! now| other)/
For some more details on lookaheads and lookbehinds, try this:
perlre - Perl regular expressions
Hope that helps.DISTRO=Arch
Registered Linux User #388732


Reply With Quote