0

String:

name@gmail.com

Checking for:

@
.com

My code

if [[ $word =~ "@" ]] 
then 
    if [[ $word =~ ".com" || $word =~ ".ca"  ]]

My problem

name@.com

The above example gets passed, which is not what I want. How do I check for characters (1 or more) between "@" and ".com"?

Dan
  • 358
  • 2
  • 3
  • 17

3 Answers3

3

You can use a very very basic regex:

[[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]]

It looks for a string being exactly like this:

at least one a-z char
@
at least one a-z char
.
at least one a-z char

It can get as complicated as you want, see for example Email check regular expression with bash script.

See in action

$ var="a@b.com"

$ [[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]] && echo "kind of valid email"
kind of valid email

$ var="a@.com"
$ [[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]] && echo "kind of valid email"
$
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Sorry, but do you think you can explain further? I don't understand what ^[a-z]@[a-z].[a-z] is doing. And what the && is doing, outside of the brackets – Dan Mar 19 '14 at 13:53
  • 1
    Use `\.` to match a literal `.` – mklement0 Mar 19 '14 at 13:54
  • 1
    @Dan sure, just updated my answer with a proper explanation. The `[[ condition ]] && echo "hello"` perform the `echo` in case the `[[ ]]` is true. So this way you can check if you are entering in the `if` condition. – fedorqui Mar 19 '14 at 13:55
1

why not go for other tools like perl:

> echo "x@gmail.com" | perl -lne 'print $1 if(/@(.*?)\.com/)'
gmail
Vijay
  • 65,327
  • 90
  • 227
  • 319
1

The glob pattern would be: [[ $word == ?*@?*.@(com|ca) ]]

? matches any single character and * matches zero or more characters

@(p1|p2|p3|...) is an extended globbing pattern that matches one of the given patterns. This requires:
shopt -s extglob

testing:

$ for word in @.com @a.ca a@.com a@b.ca a@b.org; do
    echo -ne "$word\t"
    [[ $word == ?*@?*.@(com|ca) ]] && echo matches || echo does not match
done
@.com   does not match
@a.ca   does not match
a@.com  does not match
a@b.ca  matches
a@b.org does not match
glenn jackman
  • 238,783
  • 38
  • 220
  • 352