【问题标题】:Regex / grep match on: "not this" and "that"正则表达式 / grep 匹配:“不是这个”和“那个”
【发布时间】:2017-09-13 02:57:03
【问题描述】:

从 Linux 命令行中,我想在多个文件中查找我没有使用 Fig. 引用图形引用的所有实例。

因此,当我没有在 \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)。

【问题讨论】:

  • Fig.\ref 之间的换行符怎么办?
  • @BenjaminW。 - 是的,这是一种可能。我从原始帖子中省略了它,专注于“不是这个”和“那个”所需的正则表达式。添加可选的换行符并不难。
  • 可选的换行符有很大的不同,因为 grep 逐行查看文件。如果您告诉它使用另一个字符而不是换行符,例如空字符,则匹配将返回整个文件,因为它被视为单行。
  • 这是真的。感谢您提请我注意。

标签: regex grep regex-negation


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2017-02-09
    • 1970-01-01
    • 2011-08-05
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多