如何用Python正则表达式提取字符串中的三种毫米产品尺寸?
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 characterx(addre.IGNORECASEas a flag if you need to match uppercaseXtoo)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

