I am trying to use regex to match a filename out of a path.
#!/bin/bash
regex=[^/]+?(?=.zip)
path="/home/quid/Downloads/file.zip"
if [[ $path =~ $regex ]]
then
echo "Found a match"
echo $BASH_REMATCH
fi
I should get
Found a match
file
Instead bash gives me this error
another.sh: line 2: syntax error near unexpected token `('
another.sh: line 2: `reg=[^/]+?(?=.zip)'
If I put the regex in a quotes, it no longer is recognized as regex. I have zsh 5.8 and bash 5.0.16 and it doesn't work on both shells.
How can I get bash to recognize the regex or not give me an error for using regex groups?
(?=...)
is not valid POSIX ERE syntax. Be sure you use the right regex language variant.+?
and*?
don't mean anything here.regex='([^/.]+)([.]zip)?$'
may not be exactly what you want, but its validity does demonstrate that grouping is not the part of your original expression that's illegal.regex
variable, and not use quotes when expanding that variable, to get consistent and reliable behavior.