CodexBloom - Programming Q&A Platform

Regex scenarios to Match Version Numbers with Pre-release Identifiers in Node.js - Handling Semantic Versioning

๐Ÿ‘€ Views: 57 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-06
regex node.js semver JavaScript

I've been struggling with this for a few days now and could really use some help. Hey everyone, I'm running into an issue that's driving me crazy. I'm using regex to validate version numbers following Semantic Versioning (semver) in my Node.js application. The pattern I'm currently using is intended to match versions like `1.0.0`, `2.1.0-alpha`, and `3.2.1-beta.1`. However, it's not working as expected when I try to include versions with multiple pre-release identifiers, like `1.0.0-alpha.beta`. Hereโ€™s the regex Iโ€™m using: ```javascript const semverRegex = /^(\d+)\.(\d+)\.(\d+)(?:-([\da-zA-Z-]+(\.[\da-zA-Z-]+)*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/; ``` When I test the string `1.0.0-alpha.beta`, it doesnโ€™t match, and I'm getting `null` as the output. I've tried modifying the regex in various ways, like changing the pre-release part to allow multiple segments, but I keep running into issues with unexpected captures. I've also attempted to simplify the regex to just focus on the pre-release section, but then the main version part fails to match correctly. I noticed that regex tools indicate I could be missing a quantifier that allows for multiple segments. Could anyone provide insight into what I might be missing or how to adjust my regex to properly capture all specified version formats, including pre-release identifiers? I'm currently using Node.js v16.13.0. Thanks for your help! This is part of a larger CLI tool I'm building. Is there a better approach? I'm working on a application that needs to handle this. I'd really appreciate any guidance on this.