2017-09-13 218 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)