即使编辑器不支持非贪婪匹配,如何在正则表达式中执行最小匹配 [英] 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}
使用
\textbf{test1}test2
我用regex替换为\ new {(.*)}来查找,而用\ 1替换了.
I used regex replace with \new{(.*)} to find and \1 to replace.
但是搜索总是与我的原始字符串的整个行匹配,而reus reuslt是:
however the search always match the whole line of my original string and the replace reuslt is:
}\new{\textbf{test1}}\new{test2
远远超出了我的需求.
在Java的正则表达式中,可以使用?.在一个量词使它成为一个勉强的量词之后.然后,它尝试找到最小的匹配项.因此,在Java中,我的搜索正则表达式为
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\{(.*?)\}
我需要在TeXStudio中使用相应的正则表达式搜索字符串来进行最小匹配.即使TexStudio不支持非贪婪匹配,还是可以解决这种情况吗?
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?
推荐答案
您知道嵌套最深吗?新产品可以嵌套在新产品中吗?
Do you know how deep the nesting goes at tis deepest? Can a new be nested in a new?
如果答案为是"和否",则有一个解决方案:在罗宾的解决方案\\new\{([^}]*)\}
中,将[^}]*
替换为例如[^{}]*({[^{}]*})?[^{}]*
,即任意数量的不是[^{}]*({[^{}]*})?[^{}]*
替换中间的[^{}]*
,从而像\\new\{[^{}]*({[^{}]*({[^{}]*({[^{}]*})?[^{}]*})?[^{}]*})?[^{}]*\}
一样有趣(4个级别).
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).
这篇关于即使编辑器不支持非贪婪匹配,如何在正则表达式中执行最小匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!