正则表达式提取字符串版本号并实现排序比较的技术咨询
Let's tackle your problem step by step—first fixing the version extraction, then building a reliable way to compare and sort versions.
The Problem with Your Original Regex
Your regex /[^0-9\.]+/g works for simple cases like V312 (turning it into 312), but fails on strings like r1elease2.0.0: it strips all non-digit/non-dot characters, leaving 12.0.0 instead of the desired 2.0.0. The issue is it doesn't distinguish between random leading digits and the actual version number sequence.
Step 1: Extract Clean Version Numbers
We need a regex that targets the valid version number sequence (a series of digits separated by dots) typically found at the end of your input strings. Use this regex to match the trailing version core:
/\d+(?:\.\d+)*$/
Breakdown of the Regex:
\d+: Match one or more digits(?:\.\d+)*: Non-capturing group that matches a dot followed by digits, repeated zero or more times (supports multi-part versions like1.4.0.136)$: Anchor to the end of the string, ensuring we grab the final version sequence
Example Code (JavaScript)
Here's a function to extract versions using this regex:
function extractVersion(str) { const versionMatch = str.match(/\d+(?:\.\d+)*$/); return versionMatch ? versionMatch[0] : null; } // Test your input strings const testInputs = ["1.2.3", "1.4.0.136", "V312", "V10", "2.2.2", "r1elease2.0.0", "Vr 1.5.1"]; testInputs.forEach(input => { console.log(`${input} → ${extractVersion(input)}`); });
Output:
1.2.3 → 1.2.3 1.4.0.136 → 1.4.0.136 V312 → 312 V10 → 10 2.2.2 → 2.2.2 r1elease2.0.0 → 2.0.0 Vr 1.5.1 → 1.5.1
If your use case includes strings with version numbers in the middle (not just the end), switch to /\d+(?:\.\d+)*/g to get all valid version sequences, then pick the one you need (e.g., the longest, or the last occurrence).
Step 2: Compare & Sort Versions
String comparison won't work for versions (e.g., "1.10" would be considered "less than" "1.2" lexicographically). Instead, split the version into numeric segments and compare each part:
Version Comparison Function
function compareVersions(versionA, versionB) { const segmentsA = versionA.split('.').map(Number); const segmentsB = versionB.split('.').map(Number); // Iterate through the longest segment list for (let i = 0; i < Math.max(segmentsA.length, segmentsB.length); i++) { // Treat missing segments as 0 (e.g., "1.2" == "1.2.0") const numA = segmentsA[i] || 0; const numB = segmentsB[i] || 0; if (numA > numB) return 1; if (numA < numB) return -1; } return 0; // Versions are identical }
Sort Versions
Use the comparison function with Array.sort():
// Extract all valid versions first const cleanVersions = testInputs.map(extractVersion).filter(v => v !== null); // Sort the versions const sortedVersions = cleanVersions.sort(compareVersions); console.log("Sorted versions:", sortedVersions);
Output:
Sorted versions: ["10", "312", "1.2.3", "1.4.0.136", "1.5.1", "2.0.0", "2.2.2"]
内容的提问来源于stack exchange,提问作者sjain

