用于在匹配其他条件时排除单词的正则表达式习惯用法

标签 regex sed grep regex-lookarounds

问题如下。我需要匹配每一行:

  • < 开头
  • 没有标签 <s>里面
  • 以标签 </s> 结尾

示例:

<div> blablabla </div> blablabla </s>
<div> blablabla </div> <s> blablabla </s>

我一直在尝试放置否定前瞻和通配符

^<((?!<s>).)*</s>$

并且还考虑过this trick ,但到目前为止还没有成功。我也知道

grep -v

但我想要一个纯粹的正则表达式习惯用法,然后可以在其他上下文中使用它(例如 sed)

最佳答案

您可以使用以下正则表达式:

^(?!.*<s>)<.*</s>$

说明:

^          # the beginning of the string
(?!        # look ahead to see if there is not:
  .*       #   any character except \n (0 or more times)
  <s>      #   '<s>'
)          # end of look-ahead
<          # '<'
.*         # any character except \n (0 or more times)
</s>       # '</s>'
$          # before an optional \n, and the end of the string

Live Demo

使用 grep,您可以使用 -P 选项将模式解释为 Perl 正则表达式。

grep -P '^(?!.*<s>)<.*</s>$'

您还可以考虑在上下文中使用交替运算符,将要排除的内容放在左侧(说扔掉它,它是垃圾)并将要匹配的内容放在捕获组中在右侧。

^.*<s>.*|(<.*</s>)$

Live Demo

关于用于在匹配其他条件时排除单词的正则表达式习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25069527/

相关文章:

regex - 我可以执行 'non-global' grep 并仅捕获为每行输入找到的第一个匹配项吗?

java - 如何使用正则表达式将字符串按最后一个字符拆分?

Javascript match() 和无效量词

regex - 需要与以下 json 匹配的正则表达式

Linux - 如何根据字段值从文件中删除某些行

linux - 需要更新 Linux 中最后一行以固定字符串开头的几个文件的最后一行中的子字符串

regex - 进行各种替换,但只能在字符之前

python - 如何按特定列中的字符数截断文件

linux - 如何使用 gawk/grep 打印特定的文本列表?例如我想打印txt文件中存在的所有颜色的名称

linux - Grep 从 CSV 文件中获取特定列的最新值