Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: Regular expression expanding and matching
On Sun, 25 Nov 2012 16:45:49 +0100
Mark van Dijk <lists+zsh@xxxxxxxxxxxxxx> wrote:
> I was trying to match a string with a regular expression as follows:
>
> ---
> #!/usr/local/bin/zsh
> zmodload zsh/pcre
> somestring="121125"
> todaysday="25"
> yesterday="24"
>
> set -xv
> if [[ $somestring -pcre-match \d{4}${todaysday} ]]; then
> echo "somestring matches today"
> elif [[ $somestring -pcre-match \d{4}${yesterday} ]]; then
> echo "somestring matches yesterday"
> fi
> set +xv
>
> Apparently there is no expansion of ${todaysday} and ${yesterday}. This
> is not really surprising because in regular expressions many characters
> have a different meaning.
I think the problem is different from what you think it is. Try (note
doubled backslashes):
if [[ $somestring -pcre-match \\d{4}${todaysday} ]]; then
echo "somestring matches today"
elif [[ $somestring -pcre-match \\d{4}${yesterday} ]]; then
echo "somestring matches yesterday"
fi
It's not that the $... isn't expanded, it's that the \d is also handled
like a normal command line argument. Vin's change works because in
double quotes \d remains \d because it doesn't have a special meaning.
To put it more broadly, arguments in [[ ... ]] get expanded in all the ways that make sense for generating a single word. So file name generation (globbing)
doesn't happen, and array substitution produces a single word (as if double
quotes surrounded the array), but otherwise it works like a normal command line argument. So the normal quoting rule for backslashes apply.
--
Peter Stephenson <p.w.stephenson@xxxxxxxxxxxx>
Web page now at http://homepage.ntlworld.com/p.w.stephenson/
Messages sorted by:
Reverse Date,
Date,
Thread,
Author