CodexBloom - Programming Q&A Platform

Regex for Extracting Version Numbers from Strings in JavaScript - implementing Semantic Versioning

👀 Views: 48 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-22
regex javascript semantic-versioning JavaScript

I've spent hours debugging this and I'm relatively new to this, so bear with me..... I'm trying to extract semantic version numbers (like `1.2.3`, `2.0.0-alpha`, `1.0.0-beta.1`) from a string in JavaScript using regex. My current regex looks like this: ```javascript const regex = /\b(\d+\.\d+\.\d+(-[\w.]+)?(\+\w+)?)\b/g; ``` While it works for basic version numbers, I'm working with issues with the pre-release and build metadata parts. For example, it fails to match versions like `1.0.0-alpha.1` and `2.1.0+20130313144700`. When I test it against the string: ```javascript const testString = 'Latest versions are 1.0.0-alpha.1, 1.0.0, and 2.1.0+20130313144700.'; ``` I expected to get all three versions, but I'm only able to capture `1.0.0` and `2.1.0`. The regex seems to abort after the first hyphen or plus sign. I understand semantic versioning has specific rules, but I'm struggling to incorporate all those variations. I've also tried modifying my regex to include more complex patterns, but it gets overly complicated and leads to performance optimization. Can anyone suggest a regex that can accurately match all forms of semantic versioning without compromising performance? Any help would be greatly appreciated! For context: I'm using Javascript on Linux. What am I doing wrong? This is for a microservice running on Debian. I'm open to any suggestions. This is happening in both development and production on Windows 11. Is there a simpler solution I'm overlooking?