PHP实现序列号日期提取:基于序列号确定产品保修日期
Parse Serial Number to Get Warranty Start Date
Got it, let's work through this problem together. You need to extract a warranty start date (formatted as YYYY-MM-01) from serial numbers like 217A111111111, where:
- The second and third digits (e.g.,
17in217A...) represent the last two digits of the year (so17→2017) - The fourth character is the month code:
1-9map to January-September,A=October,B=November,C=December
Here's a step-by-step solution using regex plus simple mapping logic:
Step 1: Use Regex to Capture Key Components
First, we'll write a regex to grab the year suffix and month code from the start of the serial number. The pattern ^\d(\d{2})([1-9ABC]) works here:
^anchors to the start of the string\dmatches the first irrelevant digit (like the2in217A...)(\d{2})captures the 2-digit year suffix (first group)([1-9ABC])captures the month code (second group, matches allowed characters)
Step 2: Convert Captured Values to Date Format
Once we have the two captured groups, we can transform them into the required date string:
- Year: Prepend
20to the 2-digit suffix (e.g.,17→2017) - Month: Use a mapping dictionary to convert the code to a 2-digit month number:
- For digits
1-9, pad with a leading zero (e.g.,1→01) - For letters, map
A→10,B→11,C→12
- For digits
Example Code (Python)
import re def get_warranty_date(serial_number): # Define regex pattern and month mapping pattern = r'^\d(\d{2})([1-9ABC])' month_map = {'A': '10', 'B': '11', 'C': '12'} # Match the pattern match = re.match(pattern, serial_number) if not match: return None # Handle invalid serial numbers year_suffix, month_code = match.groups() # Build year string year = f"20{year_suffix}" # Build month string if month_code.isdigit(): month = month_code.zfill(2) else: month = month_map.get(month_code) # Combine into YYYY-MM-01 format return f"{year}-{month}-01" # Test cases print(get_warranty_date("217A111111111")) # Output: 2017-10-01 print(get_warranty_date("217111111111")) # Output: 2017-01-01 print(get_warranty_date("320B999999999")) # Output: 2020-11-01
How It Works
- The regex ensures we only extract valid components from the start of the serial number
- The month mapping handles both digit and letter codes cleanly
- We pad single-digit months with a leading zero to maintain the
MMformat requirement - The function returns
Nonefor serial numbers that don't match the pattern, making it easy to handle invalid inputs
内容的提问来源于stack exchange,提问作者Marz_89
相关产品推荐
相关产品推荐

