I'm trying to capture a part of a path in bash:
Input: /Users/foo/.virtualenvs/venv-test-server
Code:
#!/bin/zsh
regex="^.*\/venv-(.*)$"
if [[ $VIRTUAL_ENV =~ $regex ]] ; then
echo "Matched!"
echo ${BASH_REMATCH[1]}
fi
Output: Matched!
But the match isn't printed. Why?
The script is specifying zsh
instead of bash
:
#!/bin/bash
^^^^
If you want to use zsh
, you need to set BASH_REMATCH
option before using =~
:
setopt KSH_ARRAYS BASH_REMATCH
The equivalent array in zsh
is match
:
% [[ foo_bar =~ (.*)_(.*) ]]
% print $match[1]
foo
% print $match[2]
bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With