Extracting numbers from an email address prior to the @ sign

Viewed 49

I am hoping someone can help me (complete newbie to regex)

I am trying to extract only the email addresses with numeric entries before the @

for example

James@hotmail.com would not be selected

J4m35@hotmail.com would be selected

The other problem i have is that each email address also has a phone number afterwards in a ten digit format.

Example

James@hotmail.com 5555511111

J4m35@hotmail.com 5555511112

Everything i have tried seems to either select the phone number too or nothing at all.

Thanks in advance and apologies if there is not enough information. I will try and answer any questions people have.

Things i have tried so far

grep -E [0-9][@] data.csv

grep -E [0-9] data.csv

grep -E \d+(?=@) data.csv (this does not complete due to a syntax error)

As i say, i'm a complete novice at this and still trying to get my head round the regex stuff

2 Answers

You can use

grep -Eo '^[^@[:space:]0-9]*[0-9][^@[:space:]]*@[^[:space:]]+' file

Details

  • ^ - start of string
  • [^@[:space:]0-9]* - zero or more chars other than a @, whitespace and a digit
  • [0-9] - a digit
  • [^@[:space:]]* - zero or more chars other than a @, whitespace and a digit
  • @ - a @ char
  • [^[:space:]]+ - one or more chars other than whitespace.

See an online demo:

s='James@hotmail.com 5555511111
J4m35@hotmail.com 5555511112
J4ll@hotmail.com 6453453344'
grep -Eo '^[^@[:space:]0-9]*[0-9][^@[:space:]]*@[^[:space:]]+' <<< "$s"
# => J4m35@hotmail.com
#    J4ll@hotmail.com

Try something like: \w*\d+\w*[@]\S*

explanation:

  • arbitrary number of word characters
  • then at least one digit
  • more arbitrary number of word characters
  • the @
  • everything behind it until the next space
Related