Python正则表达式:移除匹配结果中的可选字符
Solution to Extract Year and Month Without Optional Characters
Got it, let's fix this for you! The issue here is that your current regex includes the optional character (like the 'a' in your example) in the match, and you want to strip that out to get just the year and month digits combined. Here are two straightforward ways to do this:
Method 1: Adjust the Regex to Capture Only Needed Groups
Modify your regex to use a non-capturing group for the optional character part ((?:.?)), so you can directly grab the year and month groups and concatenate them:
import re string = 'a2017a12a' # Use non-capturing group (?:.?) for the optional character, so we only capture year and month pattern = re.compile(r"(20[0-9]{2})(?:.?)(0[1-9]|1[0-2])") result = pattern.search(string) if result: # Combine the year (group 1) and month (group 2) desired_output = result.group(1) + result.group(2) print(desired_output) # Output: '201712'
Why this works:
(?:.?)tells the regex to match the optional character but not store it as a capture group.- Groups 1 and 2 directly hold the year and month digits, so we just need to join them.
Method 2: Clean the Matched String After Capture
If you want to keep your original regex, you can take the full matched string and strip out any non-digit characters:
import re string = 'a2017a12a' pattern = re.compile(r"((20[0-9]{2})(.?)(0[1-9]|1[0-2]))") result = pattern.search(string) if result: # Extract the full matched substring, then filter out non-digits matched_substring = result.group(0) desired_output = ''.join(filter(str.isdigit, matched_substring)) print(desired_output) # Output: '201712'
Why this works:
filter(str.isdigit, matched_substring)keeps only the numeric characters from the matched string, effectively removing any optional non-digit characters in between.
内容的提问来源于stack exchange,提问作者s900n
相关产品推荐
相关产品推荐

