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

如何用Python正则表达式提取字符串中的三种毫米产品尺寸?

Extracting Dimension Formats with Python Regex

Got it, let's solve this problem of pulling those three specific dimension formats from a string using Python's regular expressions. Here's a practical, easy-to-understand approach:

Step 1: Define the Regex Pattern

The key is to account for optional spaces around the x and between the second number and mm. The pattern below will match all three of your target formats:

\d+\s*x\s*\d+\s*mm

Let's break down each part:

  • \d+: Matches one or more digits (the numerical part of the dimensions)
  • \s*: Matches zero or more spaces (handles the optional spaces in your formats)
  • x: Matches the fixed character x (add re.IGNORECASE as a flag if you need to match uppercase X too)
  • mm: Matches the fixed unit suffix

Step 2: Python Code Implementation

Here's a complete example that extracts all matching dimensions from a sample string:

import re

# Sample input string with target formats and extra noise
input_str = "Check out our products: 20x20mm, 15 x 15 mm, 25x25 mm, plus a random 50mm part."

# Regex pattern to match all three dimension formats
dimension_pattern = r'\d+\s*x\s*\d+\s*mm'

# Extract all matches
extracted_dimensions = re.findall(dimension_pattern, input_str)

# Print the results
print("Extracted dimensions:", extracted_dimensions)
# Output: Extracted dimensions: ['20x20mm', '15 x 15 mm', '25x25 mm']

Optional: Extract Numerical Values Separately

If you want to get the individual numbers instead of the full dimension string, use capturing groups in the regex:

value_pattern = r'(\d+)\s*x\s*(\d+)\s*mm'
extracted_values = re.findall(value_pattern, input_str)

print("Extracted dimension values:", extracted_values)
# Output: Extracted dimension values: [('20', '20'), ('15', '15'), ('25', '25')]

Bonus: Strict Matching (Avoid Partial Hits)

If you need to avoid matching cases where mm is followed by other letters (like 20x20mmxyz), add a negative lookahead to ensure mm isn't followed by a word character:

\d+\s*x\s*\d+\s*mm(?!\w)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:26:07