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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:34:15