如何使用正则表达式负向预测 [英] How to use regex negative lookahead
问题描述
我试图使用 egrep -o -e
从文件中获取电子邮件地址,并且遇到了线路末尾的地址问题。
I'm trying to get the email addresses from a file using egrep -o -e
and having trouble with addresses at the end of a line.
这是我的正则表达式:
Here is my regex:
egrep -o -e "[._a-zA-Z0-9]+@[._a-zA-Z0-9]+.[._a-zA-Z0-9]+" ~/myfile.txt
我意识到这并不会捕获电子邮件地址的每个变体,但是如果地址在行尾,这就是我得到的结果:
I realize this will not catch every variation of an email address, but if the address is at the end of a line this is what I get:
user@_12345@myemail.com\ul
所以我想我会尝试一个负面的向前看,但我不知道如何正确使用它。我已经在线阅读了一些内容,但我对它的工作原理感到困惑。
So I figured I'd try a negative lookahead, but I have no idea how to properly use it. I've read a few things online but I'm confused by how it works.
这是我试过的:
egrep -o -e "(?!\\[._a-zA-Z0-9]+@[._a-zA-Z0-9]+.[._a-zA-Z0-9]+)" ~/myfile.txt
Bash未找到事件失败:\\ [._ a
有何建议?
推荐答案
"[._a-zA-Z0-9]+@[._a-zA-Z0-9]+.[._a-zA-Z0-9]+"
^
here
它符合at-sign。如果你删除它,那么你的原始正则表达式不会有任何前瞻。
It matches the at-sign. If you remove it, your original regex with no lookahead will work.
此外,!
是一个特殊字符bash(历史扩张)。你必须反斜杠才能直接使用它。
Moreover, !
is a special character in bash (history expansion). You have to backslash it to use it literally.
这篇关于如何使用正则表达式负向预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!