2017-09-13 215 views
-1

从Linux命令行,我想找到在多个文件中的所有实例,我不Fig.引用数字引用。正则表达式/ grep的比赛:“不是这个”和“那个”

因此,我正在寻找每一行,当我不准备\ref{fig准确地Fig.

  1. Fig. \ref{fig:myFigure}
  2. A sentence with Fig. \ref{fig:myFigure} there.
  3. \ref{fig:myFigure}
  4. A sentence with \ref{fig:myFigure} there.

正则表达式应该忽略的情况下(1)和(2),但是发现例(3)和(4)。

+1

怎么样'Fig.'和'\ ref'之间换行符? –

+0

@BenjaminW。 - 是的,这是一种可能性。我将它从原文中省略,专注于“not this”和“that”所需的正则表达式。可选的linebreak不会难以添加。 –

+0

可选的换行符有很大的不同,因为grep逐行查看文件。如果你告诉它使用另一个字符而不是换行符,比如空字符,则匹配将返回整个文件,因为它被认为是单行。 –

回答

1

可以使用负先行,如:

^((?!Fig\. {0,1}\\ref\{fig).)*$ 

https://regex101.com/r/wSw9iI/2

Negative Lookahead (?!Fig\.\s*\\ref\{fig) 
Assert that the Regex below does not match 
Fig matches the characters Fig literally (case sensitive) 
\. matches the character . literally (case sensitive) 
\s* matches any whitespace character (equal to [\r\n\t\f\v ]) 
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy) 
\\ matches the character \ literally (case sensitive) 
ref matches the characters ref literally (case sensitive) 
\{ matches the character { literally (case sensitive) 
fig matches the characters fig literally (case sensitive)