如何仅匹配六位点分格式的版本号?
Let's tackle your problem in two key parts: ensuring we only match exactly six-segment version numbers, then correctly inserting .0 at the fourth position.
Step 1: Fix the Regular Expression
Your current regex matches any substring with six digit segments, which is why it's incorrectly catching the first six parts of a seven-segment version. To restrict it to exactly six segments for the entire string, add start (^) and end ($) anchors to the regex:
regex = re.compile(r'^\d+\.\d+\.\d+\.\d+\.\d+\.\d+$')
^forces the match to start at the very beginning of the string$forces the match to end at the very end of the string- This ensures only strings that are exactly six dot-separated digit groups will pass the check—no more false positives with seven+ segments.
Step 2: Simplify the Version Transformation
Your current code uses split('.')[-6] and similar calls, which works but is unnecessarily verbose. Since we've already confirmed the input is a six-segment version, we can split once and use direct index access to build the new version cleanly:
import re def process_version(version): regex = re.compile(r'^\d+\.\d+\.\d+\.\d+\.\d+\.\d+$') match = regex.match(version) if match: print("It's a six-digit version...") segments = version.split('.') # Insert .0 after the third segment (making it the fourth position) new_version = f"{segments[0]}.{segments[1]}.{segments[2]}.0.{segments[3]}.{segments[4]}.{segments[5]}" return new_version else: print("Not a six-digit version.") return None # Test your cases version_valid = '9.130.46.32.6.2' # Six segments - should match print(process_version(version_valid)) # Output: 9.130.46.0.32.6.2 version_invalid = '9.130.46.32.6.2.1' # Seven segments - should NOT match print(process_version(version_invalid)) # Output: Not a six-digit version. None
Key improvements here:
- Used
split('.')to get a list of all version segments (since we know it's exactly six, indexes 0-5 are safe to use) - Leveraged an f-string to construct the new version in a readable, concise way
- Wrapped logic in a function for reusability and cleaner code structure
Testing the Solution
- For the valid six-segment version, you'll get the transformed output with
.0inserted at the fourth position - For the seven-segment version, the regex won't match, so the function returns
Noneand prints a clear message
内容的提问来源于stack exchange,提问作者carte blanche

