Bash: Check If a String Matches a Regex
How to test a string against a regular expression in Bash with [[ =~ ]], what BASH_REMATCH captures, common quoting pitfalls, portable alternatives, and Unicode caveats.
The short answer
In Bash, the standard way to check whether a string matches a regular expression is the =~ operator inside double brackets: [[ $string =~ $regex ]]. It is built into the shell, needs no external program, and can capture matched groups. It suits validation and parsing inside scripts that are guaranteed to run under Bash. The decisive tradeoff is portability and regex flavor: it does not work in plain POSIX sh, and it uses POSIX extended regular expressions (ERE), not the Perl-style syntax many developers expect. If you only need a fixed prefix, suffix or substring check, a glob comparison or a case statement is simpler and easier to read.
#!/usr/bin/env bash
re='^[0-9]{3}-[0-9]{4}$'
input='555-1234'
if [[ $input =~ $re ]]; then
echo "match"
else
echo "no match"
fi
What the test actually does
The =~ operator does not modify the string. It compiles the right-hand side as a POSIX extended regular expression using the system's regex library and reports the result through its exit status: 0 when the string matches, 1 when it does not, and 2 when the regular expression itself is invalid. Treating any nonzero status as "no match" hides syntax errors, so it can be worth distinguishing the cases while developing a pattern.
[[ $s =~ $re ]]
case $? in
0) echo "match" ;;
1) echo "no match" ;;
2) echo "invalid regex: $re" >&2 ;;
esac
The only side effect of a successful match is the BASH_REMATCH array. Element 0 holds the part of the string that matched the whole expression, and elements 1, 2 and so on hold the parenthesized capture groups in order. The array is overwritten by the next =~ test, so copy the values you need into ordinary variables right away.
date_re='^([0-9]{4})-([0-9]{2})-([0-9]{2})$'
if [[ $d =~ $date_re ]]; then
year=${BASH_REMATCH[1]}
month=${BASH_REMATCH[2]}
day=${BASH_REMATCH[3]}
fi
Rules behind most failed matches
- Matching is unanchored. [[ abc123 =~ [0-9]+ ]] succeeds because a substring matches. For whole-string validation, start the pattern with ^ and end it with $.
- Do not quote the regex. Since Bash 3.2, any quoted part of the right-hand side is matched as literal text, so [[ $s =~ "^[0-9]+$" ]] looks for the characters ^[0-9]+$ rather than digits. Quoting the left-hand variable is optional inside double brackets because no word splitting happens there.
- Keep the pattern in a variable. Writing re='...' and then [[ $s =~ $re ]] avoids having to escape spaces, parentheses and other characters the shell would otherwise interpret.
- Use ERE syntax only. Shorthands such as \d and \s, lazy quantifiers and lookahead or lookbehind are not part of POSIX ERE. Use bracket classes such as [[:digit:]] and [[:space:]] instead. Some systems' regex libraries accept extras like \w or \b, but that is not portable and should be tested on the machine that will run the script.
- Case sensitivity is controlled by the shell. Running shopt -s nocasematch makes =~ comparisons case-insensitive until it is turned off again.
s='42'
[[ $s =~ ^[0-9]+$ ]] && echo "unquoted: match"
[[ $s =~ "^[0-9]+$" ]] && echo "quoted: match" # not printed: looks for the literal text ^[0-9]+$
The literal-quoting rule is also useful. When part of the pattern comes from a variable that may contain regex metacharacters, such as a dot in a file extension, quoting just that part makes it match literally while the rest of the expression keeps its regex meaning.
ext='tar.gz'
# The quoted part is literal, so the dot in $ext matches only a dot
[[ $file =~ [.]"$ext"$ ]] && echo "compressed tarball"
Alternatives and when they fit better
| Method | Example | Pattern type | Good fit | Main limits |
| [[ =~ ]] | [[ $s =~ $re ]] | POSIX ERE | Validation and group capture in Bash scripts | Bash-specific; ERE only |
| [[ == ]] with a glob | [[ $s == *.log ]] | Glob | Prefix, suffix and substring checks | No repetition counts unless extglob is enabled |
| case statement | case $s in *.log) ... ;; esac | Glob | Portable POSIX sh scripts | Glob patterns only |
| grep -E | printf + grep -Eq "$re" | ERE (GNU grep also offers -P for Perl-style syntax) | POSIX sh scripts that need a real regex | Starts an extra process; tests each line separately |
| expr | expr "$s" : 're' | BRE, anchored at the start | Very old shells | Awkward syntax; prints the match length |
#!/bin/sh
re='^[0-9]+$'
if printf '%s\n' "$s" | grep -Eq "$re"; then
echo "match"
fi
One behavioral difference matters for validation. grep works line by line, so a string containing a newline passes if any single line matches, and ^ and $ anchor to each line. With [[ =~ ]], ^ and $ refer to the start and end of the whole string. If input can contain newlines, the grep approach can accept values that the Bash test would reject.
Will the check still work after copying or sharing the script?
- Shell choice: a script that starts with #!/bin/sh may run under a shell such as dash that has no [[ ]] at all and fails with a "not found" style error. Use a Bash shebang, or switch to case or grep for POSIX sh.
- zsh differences: zsh supports =~, but by default stores captures in $MATCH and $match rather than BASH_REMATCH unless its BASH_REMATCH option is set.
- Pasted snippets: code copied from web pages, chat apps or word processors can pick up typographic quotes or non-breaking spaces, which the shell does not treat as quotes or whitespace. If a pasted test fails for no visible reason, retype the quotes and spaces.
- Windows line endings: data read from a file saved with CRLF line endings carries a trailing carriage return, so a pattern ending in $ fails on every line. Strip it before testing.
- Readability for the next person: give pattern variables descriptive names and add a short comment describing what a valid value looks like, since ERE patterns are hard to read at a glance.
while IFS= read -r line; do
line=${line%$'\r'} # drop a trailing carriage return
[[ $line =~ ^[0-9]+$ ]] && echo "numeric: $line"
done < input.txt
Unicode, combining marks and emoji
Regex matching in Bash follows the current locale. In a UTF-8 locale, the dot and bracket expressions generally match one code point, not one user-perceived character; in the C or POSIX locale they match single bytes. That distinction affects length checks such as ^.{1,10}$. An accented letter can be stored either as one precomposed code point or as a base letter followed by a combining mark, and many emoji, including flags and family sequences joined with zero-width joiners, consist of several code points. A string that looks like ten characters can therefore fail a ten-character limit, and two strings that look identical may not match the same pattern.
Bash does not normalize text before matching. If equivalent spellings must match, normalize input with an external tool first. Ranges such as [a-z] can also behave differently across locales; use named classes like [[:lower:]] for letters, or set LC_ALL=C for the duration of the test when you deliberately want ASCII and byte semantics.
Limits of this overview
The behavior described here is documented Bash and POSIX regex behavior; no environment-specific tests, timings or benchmarks were supplied or performed for this article. Support for non-POSIX escapes and the exact handling of multibyte characters depend on the system's regex library and locale settings, so confirm critical patterns on the target system by checking bash --version and running a few representative inputs, including edge cases with newlines, carriage returns and non-ASCII text.