Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH_REMATCH doesn't capture

Tags:

regex

bash

zsh

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?

like image 223
melbic Avatar asked Jul 29 '15 08:07

melbic


Video Answer


2 Answers

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
like image 97
falsetru Avatar answered Sep 22 '22 23:09

falsetru


The equivalent array in zsh is match:

% [[ foo_bar =~ (.*)_(.*) ]]
% print $match[1]
foo
% print $match[2]
bar
like image 31
chepner Avatar answered Sep 19 '22 23:09

chepner