-
Notifications
You must be signed in to change notification settings - Fork 732
Open
Description
Hello,
today I was writing an application for a bit of CI-infrastructure of mine that needs to handle semver numbers from applications. Since I prefer to write my CI code in plain bash, I came up with a regex that one can perform in bash to match semver. This differs slightly from the example for numbered capture groups since POSIX regex (which is what bash uses), as far as I know, has no concept of non-matching capture groups. Here's what I came up with:
# Regex for a semver digit
D='0|[1-9][0-9]*'
# Regex for a semver pre-release word
PW='[0-9]*[a-zA-Z-][0-9a-zA-Z-]*'
# Regex for a semver build-metadata word
MW='[0-9a-zA-Z-]+'
if [[ "$INPUT" =~ ^($D)\.($D)\.($D)(-(($D|$PW)(\.($D|$PW))*))?(\+($MW(\.$MW)*))?$ ]]; then
MAJOR="${BASH_REMATCH[1]}"
MINOR="${BASH_REMATCH[2]:-""}"
PATCH="${BASH_REMATCH[3]:-""}"
PRE_RELEASE="${BASH_REMATCH[5]:-""}"
BUILD_METADATA="${BASH_REMATCH[10]:-""}"
fi
The individual parts are captured as follows:
- Capture group 1: Major
- Capture group 2: Minor
- Capture group 3: Patch
- Capture group 5: Prerelease
- Capture group 10: Build metadata
Here is the fully-expanded regex pattern:
^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(\+([0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*))?$
Maybe this will save someone else an hour of playing with regular expressions. :)
mordekasgstas-at-ibm, PepekT, connorhsm, dmitrytavern, fabasoad and 4 more
Metadata
Metadata
Assignees
Labels
No labels