RegEx with \d doesn’t work in if-else statement with [[
i wrote the following script. It will be used in a build process later. My goal is to decide whether it's a pre release or a release. To archive this i compare $release to a RegEx. If my RegEx matches it's a pre release, if not it's a release.
#/bin/bash
release="1.9.2-alpha1"
echo "$release"
if [[ "$release" =~ \d+\.\d+\.\d+[-]+.* ]];then
echo "Pre"
else
echo "Release"
fiBut as result i always end up with the following:
~$ bash releasescript.sh
1.9.2-alpha1
ReleaseVersion:
Ubuntu 18.04.1 LTSI used this editor to test my RegEx. I'm stuck for at least 6h, so i would appreciate some help greatly.
01 Answer
\d and \w don't work in POSIX regular expressions, you could use [[:digit:]] though
#/bin/bash
release="1.9.2-alpha1"
echo "$release"
LANG=C # This needed only if script will be used in locales where digits not 0-9
if [[ "$release" =~ ^[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+-+ ]];then
echo "Pre"
else
echo "Release"
fiI have tested this script, it output "Pre" for given $release
Checked out your regex builder, it works only with perl compatible and javascript regex, while you need posix, or posix extended.
By @dessert:
4
[0-9]is the shorter alternative to[[:digit:]]. As the beginning of the string is to be matched, one should add^, while.*at the end is superfluous:^[0-9]+\.[0-9]+\.[0-9]+-+– using a group this can be further shortened to:^([0-9]+\.){2}[0-9]+-+