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

Python正则表达式:匹配斜杠分隔数字或末尾为XXX的格式

Python Regex for Matching Number/XXX Formats

Alright, let's tackle this regex requirement step by step. First, let's recap all the valid patterns we need to capture:

  • Single positive integer (e.g., 80)
  • 2 components: either [number]/[number] or [number]/XXX (e.g., 80/60, 80/XXX)
  • 3 components: either [number]/[number]/[number] or [number]/[number]/XXX (e.g., 80/60/75, 80/60/XXX)
  • 4 components: either [number]/[number]/[number]/[number] or [number]/[number]/[number]/XXX (e.g., 80/60/75/50, 80/60/75/XXX)

The Regex Pattern

Here's the regex that covers all these cases perfectly, anchored to match the entire string (so partial matches don't sneak through):

import re

# Basic version (allows leading zeros, e.g., 080 is valid)
regex_pattern = r'^\d+(?:/\d+){0,2}(?:/(?:\d+|XXX))?$'

# Test it with your example cases
test_cases = [
    "80", "80/60", "80/60/75", "80/60/75/50",
    "80/XXX", "80/60/XXX", "80/60/75/XXX",
    # Invalid cases that should fail
    "80/", "/60", "80/XX", "80/60/75/80/90"
]

for case in test_cases:
    match = re.fullmatch(regex_pattern, case)
    print(f"Case '{case}': {'Valid' if match else 'Invalid'}")

Breakdown of the Regex

Let's unpack each part so you understand how it works:

  • ^ and $: These are start/end anchors, ensuring we match the entire input string (not just a substring)
  • \d+: Matches one or more digits (covers the first number in all formats)
  • (?:/\d+){0,2}: A non-capturing group that matches a slash followed by digits, repeated 0 to 2 times. This handles the middle numbers when we have 3 or 4 components (since the first number plus 2 middle ones gives us 3 numbers before the final optional part)
  • (?:/(?:\d+|XXX))?$: An optional non-capturing group that matches a slash followed by either digits or the exact string XXX. The trailing ? makes this whole part optional, which covers the single-number case.

Optional: Disallow Leading Zeros

If you want to reject numbers with leading zeros (except for the number 0 itself), use this adjusted pattern instead:

# Strict version (no leading zeros except for "0")
regex_pattern_strict = r'^(?:0|[1-9]\d*)(?:/(?:0|[1-9]\d*)){0,2}(?:/(?:(?:0|[1-9]\d*)|XXX))?$'

This replaces \d+ with (?:0|[1-9]\d*), which matches either 0 or a number starting with a non-zero digit followed by any number of digits.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:12:53