Home > Mobile >  How to use regex in shell with special characters?
How to use regex in shell with special characters?

Time:06-23

I tried follow but it can't work:

condition="^(?:http(s)?:\/\/)?[\w.-] (?:\.[\w\.-] ) [\w\-\._~:/?#[\]@!\$&'\*\ ,;=.] $"
if [[ $1 =~ condition ]]
then
        echo fine
else
        echo bad
fi

It's used to determine whether the first param is valid.

CodePudding user response:

You can use

^(https?://)?[[:alnum:]_.-] (\.[[:alnum:]_.-] ) [][[:alnum:]_.~:/?#@!$&'* ,;=.-] $

This means:

  • No non-capturing groups, all (?: need to be replaced with (
  • \w might not be supported in all environments, it can be replaced with [[:alnum:]_] pattern
  • You can't escape special chars inside bracket expressions and -, ] and ^ need to follow "smart placement" rule (] should be at the start of the bracket expression and - must be at the end).

See an online demo:

#!/bin/bash
url='http://www.blah.com'
condition='^(https?://)?[[:alnum:]_.-] (\.[[:alnum:]_.-] ) [][[:alnum:]._~:/?#@!$&'"'"'* ,;=.-] $'
if [[ "$url" =~ $condition ]]
then
    echo fine
else
    echo bad
fi

Output: fine

Note:

  • $1 in your script should be quoted, "$1"
  • The condition must be prepended with $
  • Make sure you define the pattern with single quotes to avoid issues with some special chars.
  • Related