本文介绍了正则表达式惰性匹配不匹配贪婪表达式匹配的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下文本文件(称为 test.txt ):

  \centerline {\includegraphics [width = 0.50 \columnwidth] {example_graph.pdf}} 
\centerline {\includegraphics [width = 0.5 \columnwidth] {coarse_grain_illustration.png}}
\centerline {\includegraphics [width = 0.8 \columnwidth] {1y26_energy_dists.pdf}}

如果我用贪婪的匹配进行搜索,我会得到我期望的结果:

pre $ [user @ host test] $ grep '\\includegraphics。* df'test.txt
\centerline {\includegraphics [width = 0.50 \columnwidth] {example_graph.pdf}}
\centerline {\includegraphics [ width = 0.8 \columnwidth] {1y26_energy_dists.pdf}}
================================= ================================================== == b

然而,如果我使用懒惰评估,我不会得到任何结果:

  [user @ host test] $ grep'\\includegraphics。*?df'test.txt 
=================== ================================================== ======================================

什么给了?为什么使用懒惰评估不匹配本质上相同的模式?

解决方案

。*?或懒惰模式在任何地方都不受支持。你将不得不在Perl模式下使用 grep -P 或grep来实现它。


Suppose I have the following text file (called test.txt):

\centerline{\includegraphics[width=0.50 \columnwidth]{example_graph.pdf}}
\centerline{\includegraphics[width=0.5 \columnwidth]{coarse_grain_illustration.png}}
\centerline{\includegraphics[width= 0.8 \columnwidth]{1y26_energy_dists.pdf}}

If I search with greedy matching, I get the results I expect:

[user@host test]$ grep '\\includegraphics.*df' test.txt
\centerline{\includegraphics[width=0.50 \columnwidth]{example_graph.pdf}}
\centerline{\includegraphics[width= 0.8 \columnwidth]{1y26_energy_dists.pdf}}
===========================================================================================================

If I use lazy evaluation, however, I get no results:

[user@host test]$ grep '\\includegraphics.*?df' test.txt
===========================================================================================================

What gives? Why does using lazy evaluation not match what is essentially the same pattern?

解决方案

.*? or lazy mode is not supported everywhere. You will have to use grep -P or grep in perl mode to achieve it.

这篇关于正则表达式惰性匹配不匹配贪婪表达式匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:19