I have a text file that contains email addresses and some information.
I would like to know how can I extract those email address using R or the terminal?
I've read that I can used some regular expression that would match an email address such as
"^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$"
But what command or function shall I used to extract those emails?
There are no pattern in the text file. The command or function should just do a search on the document and extract the email addresses.
Lets take an unstructured example file:
Then if you do:
it extracts a vector of all the emails, including when there's more than one on a line. I don't think it will find email addresses broken over line breaks, but if you paste the read lines together it might do that too:
In this case there's only one line in
myText
because we pasted all the lines together, so there's only one element in the returned listemails
object.Note that regex string isn't a strict definition of a valid email address. For example, it limits itself to addresses that are between 2 and 4 characters after the last dot. So it doesn't match
fred@foo.fnord
. There are top level domains that are longer than four characters so you may need to modify the regex.Also, it only matches alphanumeric and dot in the name part - so valid addresses such as
foo+bar@google.com
won't match.A regex that fixes these two issues might be:
but it probably has other issues and you'd be better of searching for a better email address regex online. I say better, because a perfect one doesn't exist...
This can also work :
Read your file into R and use
grep
.This will return the whole line that the email appears on, if there is other information on that line you will need to split it up first using something like
strsplit