Regex Matching in Shell

Level 4185 keystrokes

[[ string =~ regex ]] tests a string against an extended regular expression, and BASH_REMATCH holds the matched text. Here a simple email pattern matches "user@example.com".

Shell code

# The string to check
1email="user@example.com"
# A simple email regex: name@domain.tld with a TLD of 2+ letters
# Single quotes keep the backslash in \. as is
2pattern='^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# =~ matches a regex; $pattern must stay unquoted, or it is matched as plain text
3if [[ $email =~ $pattern ]]; then
# BASH_REMATCH[0] holds the whole matched text
4 echo "Valid email: ${BASH_REMATCH[0]}"
5else
# Runs when the pattern does not match
6 echo "Invalid email"
7fi

Output

Valid email: user@example.com
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • -× 10
  • "× 6
  • [× 6
  • ]× 6
  • .× 4
  • $× 4
  • +× 3
  • =× 3
  • _× 2
  • '× 2

More Shell examples at level 4

← Shell typing practice