Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a non greedy regex query in notepad++?

I am writing a paper with latex and accidentally wrote \cite[] instead of \cite{}. I could just go over the whole document by hand but I want to know how to do this in notepad++ using regexes.

I initially tried \\cite\[(.*)\] and replace with \cite{\1} which works for simple cases such as

\cite[hello world] blah blah 

However if there are two or more citations in a paragraph it matches all of them. So for example

\cite[aaa]\cite[bbb] something here \cite[ccc]

matches the whole line

How can I get a non greedy match so that the above line would be matched as 3 separate matches and the result of a replace command should give me

\cite{aaa}\cite{bbb} something here \cite{ccc}
like image 826
twerdster Avatar asked Aug 24 '13 06:08

twerdster


People also ask

How do I make something not greedy in regex?

To make the quantifier non-greedy you simply follow it with a '?' the first 3 characters and then the following 'ab' is matched. greedy by appending a '?' symbol to them: *?, +?, ??, {n,m}?, and {n,}?.

Can I use regex in Notepad?

Using Regex to find and replace text in Notepad++ In all examples, use select Find and Replace (Ctrl + H) to replace all the matches with the desired string or (no string). And also ensure the 'Regular expression' radio button is set.

What is lazy regex?

'Lazy' means match shortest possible string. For example, the greedy h. +l matches 'hell' in 'hello' but the lazy h.

How do you make a non-greedy python regex?

Non-greedy quantifiers match their preceding elements as little as possible to return the smallest possible match. Add a question mark (?) to a quantifier to turn it into a non-greedy quantifier.


1 Answers

Use a reluctant (aka non-greedy) expression:

\\cite\[(.*?)] 

See a live demo.

The addition of the question mark changes the .* from greedy (the default) to reluctant so it will consume as little as possible to find a match, ie it won't skip over multiple search terms matching start of one term all the way to the end of another term.

ie using .* the match would be

foo \cite[aaa]\cite[bbb] something here \cite[ccc] bar
    ^----------------------1---------------------^

but with .*? the matches would be:

foo \cite[aaa]\cite[bbb] something here \cite[ccc] bar
    ^---1----^^----------------2-----------------^

Minor note: ] does not need escaping.

like image 93
Bohemian Avatar answered Sep 17 '22 13:09

Bohemian