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

独自空忆成欢 提交于 2019-12-22 03:43:16

问题


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}

回答1:


Use a reluctant (aka non-greedy) expression:

\\cite\[(.*?)\] 

The addition of the question mark changes the .* from greedy (the default) to reluctant (non-greedy), which means it will consume as little as possible to find a match, which means it won't skip over multiple search terms such that it matches using the open square bracket if the first cite and the closing square bracket of the last cite.

See a live demo of this regex working with the sample in the question.




回答2:


Better to use a more precises expression in the first place:

\\cite\[([^[\]]*)\]

You must be using Notepad++ version 6 or higher (they upgraded to the PCRE regex engine at V6).



来源:https://stackoverflow.com/questions/18415871/how-can-i-do-a-non-greedy-regex-query-in-notepad

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!