0

I saw in bash regex match string that I should compare regexes with =~.

Tried the following:

if [[ "____[9 / 101] Linking" =~ "[0-9]*" ]]; then echo "YES"; fi

And nothing is printed...

Tried without the quotes:

if [[ "____[9 / 101] Linking" =~ [0-9]* ]]; then echo "YES"; fi

And it works fine. But what to do if my regex contains white spaces (quotes required)?

Elad Weiss
  • 3,662
  • 3
  • 22
  • 50

2 Answers2

3

Put your regex in a variable. You are free to use quotes when defining the variable:

$ re="[0-9]*"  ; [[ "____[9 / 101] Linking" =~ $re ]] && echo "YES"
YES
$ re="9 /"  ; [[ "____[9 / 101] Linking" =~ $re ]] && echo "YES"
YES

Since the reference to $re inside [[...]] is unquoted, the value of $re is treated as a regex. Anything on the right-side of =~ that is quoted, however, will be treated as a literal string.

Notes

In regular expressions, as opposed to globs, * means zero or more of the preceding. Thus [0-9]* is considered a match even if zero characters are matching:

$ re="[0-9]*"  ; [[ "____[a / bcd] Linking" =~ $re ]] && echo "YES"
YES
$ re="[0-9]"  ; [[ "____[a / bcd] Linking" =~ $re ]] && echo "YES"
$ 

If you want to match one or more digits, use [0-9]+.

John1024
  • 109,961
  • 14
  • 137
  • 171
2

Precede the whitespace with a \:

if [[ "____[9 / 101] Linking" =~ [0-9]*\ /\ [0-9]* ]]; then echo "YES"; fi