Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Negative Lookahead in Regex to Delete unwanted Lines

Tags:

I need help regarding using negative lookahead. I am using Notepad++ and I want to delete all lines except the lines that contain <title>(.*)</title>

I tried a couple of things but that didnt work.

^.*(?!<title>).*</title>
^.*(?!<title>.*</title>)
like image 955
Atif Avatar asked Mar 09 '13 18:03

Atif


People also ask

What is negative look ahead in regex?

A negative look-ahead, on the other hand, is when you want to find an expression A that does not have an expression B (i.e., the pattern) after it. Its syntax is: A(?!B) . In a way, it is the opposite of a positive look-ahead.

What is Lookbehind in regex?

Lookbehind, which is used to match a phrase that is preceded by a user specified text. Positive lookbehind is syntaxed like (? <=a)something which can be used along with any regex parameter. The above phrase matches any "something" word that is preceded by an "a" word.

Can I use regex lookahead?

Lookahead assertions are part of JavaScript's original regular expression support and are thus supported in all browsers.

Does grep support negative lookahead?

You probably cant perform standard negative lookaheads using grep, but usually you should be able to get equivalent behaviour using the "inverse" switch '-v'. Using that you can construct a regex for the complement of what you want to match and then pipe it through 2 greps.


1 Answers

You are close:

^(?!.*<title>.*</title>).*

By this regex ^.*(?!<title>.*</title>), the regex engine will just find some position that it cannot find <title>.*</title> (end of line is one such valid position).

You need to make sure that, from the start of the line, there is no way you can find <title>.*</title> anywhere in the line. That is what my regex does.

like image 105
nhahtdh Avatar answered Sep 30 '22 08:09

nhahtdh