How to check for strings between certain strings in unix scripting?

前端 未结 3 513
野性不改
野性不改 2021-01-26 11:55

String:

name@gmail.com

Checking for:

@
.com

My code

if [[ $word =~ \"@\" ]] 
then 
    if [[          


        
相关标签:
3条回答
  • 2021-01-26 12:06

    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"
    $
    
    0 讨论(0)
  • 2021-01-26 12:07

    why not go for other tools like perl:

    > echo "x@gmail.com" | perl -lne 'print $1 if(/@(.*?)\.com/)'
    gmail
    
    0 讨论(0)
  • 2021-01-26 12:09

    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
    
    0 讨论(0)
提交回复
热议问题