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)?

2
  • note [0-9]* matches zero or more occurrences so it will always be true. Use [0-9][0-9]* to match one or more digits. Commented Nov 19, 2017 at 7:11
  • 2
    If you enclose the right part of =~ in quotation marks, =~ works like ==. Commented Nov 19, 2017 at 7:26

2 Answers 2

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]+.

Sign up to request clarification or add additional context in comments.

Comments

2

Precede the whitespace with a \:

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

1 Comment

Accepted for the fastest working solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.