You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell正则匹配连字符(-)或空值及SemVer版本合规校验问题

Solution for SemVer Validation in Bash

To fix your script and correctly match SemVer versions including pre-release suffixes (like 0.3.5-7.1.0-7), we need to adjust the extended glob pattern to account for the optional pre-release and build metadata components of SemVer. Here's how to do it:

Key Issues with Your Original Attempt

Your initial tweak [-]* only matches zero or more hyphens, which doesn't account for the alphanumeric/dot characters that follow the hyphen in valid pre-release versions. We need to match the hyphen plus one or more valid characters for pre-release identifiers.

Corrected Script

First, ensure extended globbing is enabled (it's required for the +([...]) syntax). Then update the pattern to include optional pre-release and build metadata parts:

# Enable extended globbing (required for the pattern syntax)
shopt -s extglob

# Test version (can be replaced with your variable)
versionA=0.3.5-7.1.0-7

if [[ $versionA = +([[:digit:]]).+([[:digit:]]).+([[:digit:]])?(-+([[:alnum:].-]))?(\++([[:alnum:].-])) ]]; then
    echo "Version is compliant with SemVer"
else
    echo "Version is not compliant to SemVer standard. Use formats like x.y.z, x.y.z-pre.release, or x.y.z+build.metadata"
fi

Breakdown of the Pattern

Let's break down the extended glob pattern to understand what each part does:

  • +([[:digit:]]).+([[:digit:]]).+([[:digit:]]): Matches the core SemVer x.y.z where x, y, z are one or more digits.
  • ?(-+([[:alnum:].-])): Optional pre-release component:
    • ?(): Matches zero or one occurrence of the inner pattern.
    • -: Literal hyphen starting the pre-release.
    • +([[:alnum:].-]): One or more characters that are alphanumeric, dot, or hyphen (valid pre-release identifier characters).
  • ?(\++([[:alnum:].-])): Optional build metadata component (added for completeness):
    • \+: Literal plus starting build metadata.
    • +([[:alnum:].-]): One or more valid build metadata characters.

Note on Strict SemVer Compliance

This pattern provides a practical, flexible check that covers most common SemVer use cases. For strict compliance (e.g., preventing leading zeros in numeric pre-release identifiers like 1.0.0-01), you'd need a more complex regex. However, this version works well for most validation scenarios.

内容的提问来源于stack exchange,提问作者MelDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:55:32