Search code examples
regexreplacenon-greedy

How to do the smallest match in regex replace even if the editor does not support non-greedy match


I using regex search to replace the following string:

\new{}\new{\textbf{test1}}\new{test2}

with

\textbf{test1}test2

I used regex replace with \new{(.*)} to find and \1 to replace.

however the search always match the whole line of my original string and the replace reuslt is:

}\new{\textbf{test1}}\new{test2

far from what I need.

In regex expression in Java, you can use a ? after a quantifier makes it a reluctant quantifier. It then tries to find the smallest match. So in java, my search regex expression would be

\\new\{(.*?)\}

I need the corresponding regex search string in TeXStudio to do the smallest match. Anyway to still work through for this case even if TexStudio does not support non-greed match?


Solution

  • Do you know how deep the nesting goes at tis deepest? Can a new be nested in a new?

    If the answers are 'yes' and 'no' there is a solution: in Robin's solution \\new\{([^}]*)\} replace the [^}]* with, for example, [^{}]*({[^{}]*})?[^{}]* which is "any number of characters that are not {}" followed by maybe an opening bracket, a number of non-brackets, and a closing one, followed by again zero or more not-brackets. This will match nesting up to two. For every extra level of nesting, you need to replace the middle [^{}]* with another [^{}]*({[^{}]*})?[^{}]* leading to fun like \\new\{[^{}]*({[^{}]*({[^{}]*({[^{}]*})?[^{}]*})?[^{}]*})?[^{}]*\} (4 levels).

    Example for 2 levels
    Example for 4 levels