问题如下。我需要匹配每一行:
- 以
<
开头 - 没有标签
<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
使用 grep,您可以使用 -P
选项将模式解释为 Perl 正则表达式。
grep -P '^(?!.*<s>)<.*</s>$'
您还可以考虑在上下文中使用交替运算符,将要排除的内容放在左侧(说扔掉它,它是垃圾)并将要匹配的内容放在捕获组中在右侧。
^.*<s>.*|(<.*</s>)$
关于用于在匹配其他条件时排除单词的正则表达式习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25069527/