In bash you can use [[ pattern =~ regex ]]
to match on a conditional:
if [[ "hello world" =~ ^hell ]]; then
echo Match
else
echo No match
fi
The syntax is simple: [[ INPUT =~ REGEX ]]
.
Grouping match (REGEX)
can be found in the array variable BASH_REMATCH
:
URL=https://example.com
if [[ "$URL" =~ ^https?://([^/]+) ]]; then
FOUND_DOMAIN=${BASH_REMATCH[1]}
echo "Domain: $FOUND_DOMAIN"
else
echo "Invalid URL"
fi