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

如何仅匹配六位点分格式的版本号?

Fixing Version Number Matching & Transformation

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 .0 inserted at the fourth position
  • For the seven-segment version, the regex won't match, so the function returns None and prints a clear message

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:10:03