苏灵素
苏灵素

Reputation: 45

How to use regex in shell with special characters?

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.

Upvotes: 1

Views: 1598

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

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.

Upvotes: 1

Related Questions