If statement with [[ ]] and regex not working as expected

Using BASH:

$ if [[ "2013-01-18 10:58:00" == "20[0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:00" ]]; then echo "true"; else echo "false"; fi
false

Mike

Drop the quotes on the right-hand side.

1 Like

try:

if expr "2013-01-18 10:58:00" : "20[0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:00" >/dev/null; then echo "true"; else echo "false"; fi
1 Like

That's not really a regex, that's still a glob. Meaning, you can do the same thing in a more portable case statement:

case "$VAR" in
20[0-9][0-9]-[0-1][0-9]-[0-3][0-9]" "[0-2][0-9]:[0-5][0-9]:00)
        echo "match" ;;
*) echo "no match" ;;
esac
1 Like
$ if [[ "2013-01-18 10:58:00" == 20[0-9][0-9]-[0-1][0-9]-[0-3][0-9]" "[0-2][0-9]:[0-5][0-9]:00 ]]; then echo "true"; else echo "false"; fi
true

---------- Post updated at 09:28 AM ---------- Previous update was at 09:27 AM ----------

true

---------- Post updated at 09:30 AM ---------- Previous update was at 09:28 AM ----------

Do you mean that normal shell expansion (a subset of RegEx rules) works?

Thanks to all three of you.

Mike

Shell expansion works in case statements, yes. But it's not a regex. It's not even a subset of regex... It looks similar but acts very different.

  • isn't a wildcard in regex, it's a modifier. "" isn't a valid regex, but "." would be (where . is special character meaning 'any character').

BASH does have an operator for regex, but you're not using it.

1 Like