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 check1email="user@example.com"# A simple email regex: name@domain.tld with a TLD of 2+ letters# Single quotes keep the backslash in \. as is2pattern='^[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 text3if [[ $email =~ $pattern ]]; then # BASH_REMATCH[0] holds the whole matched text4 echo "Valid email: ${BASH_REMATCH[0]}"5else # Runs when the pattern does not match6 echo "Invalid email"7fiOutput
Valid email: user@example.com
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