Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Regex "Not" (negative lookahead)

People also ask

What is a positive lookahead regex?

The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign. You can use any regular expression inside the lookahead (but not lookbehind, as explained below). Any valid regular expression can be used inside the lookahead.

What is use of ?: In regex?

'a' (which in this case ?: is doing it is matching with a string but it is excluding whatever comes after it means it will match the string but not whitespace(taking into account match(numbers or strings) not additional things with them.)

What is in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.

What is lookahead and Lookbehind?

The lookbehind asserts that what immediately precedes the current position is a lowercase letter. And the lookahead asserts that what immediately follows the current position is an uppercase letter.


You can use a negative lookahead (documented under "Extended Patterns" in perlre):

/^\/(?!bob\/)/

TLDR: Negative Lookaheads

If you wanted a negative lookahead just to find "foo" when it isn't followed by "bar"...

$string =~ m/foo(?!bar)/g;

Working Demo Online

Source

To quote the docs...

(?!pattern)

(*nla:pattern)

#(*negative_lookahead:pattern)

A zero-width negative lookahead assertion. For example /foo(?!bar)/ matches any occurrence of "foo" that isn't followed by "bar". Note however that lookahead and lookbehind are NOT the same thing. You cannot use this for lookbehind. (Source: PerlDocs.)

Negative Lookaheads For Your Case

The accepted answer is great, but it leaves no explanation, so let me add one...

/^\/(?!bob\/)/
  • ^ — Match only the start of strings.
  • \/ — Match the / char, which we need to escape because it is a character in the regex format (i.e. s/find/replacewith/, etc.).
  • (?!...) — Do not match if the match is followed by ....
  • bob\/ — This is the ... value, don't match bob/', once more, we need to escape the /`.