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

Python正则表达式匹配:兼容带*与不带*开头的目标内容

Fixing Your Regex to Match Entries With or Without Leading *

Hey there! Let's work through why your regex isn't catching entries without a leading * and how to fix it.

The Issue With Your Current Regex

Your pattern [/*][AB]:{equipo}#? starts with [/*], which tells the regex to require either a / or * at the start of the match. That's exactly why entries like A:PED77MCY04 # (no leading *) aren't being matched—they don't meet that mandatory first character rule.

The Simple Fix: Make the Leading Character Optional

To match entries that may or may not start with * (or /), we just need to add a ? after the [/*] character class. The ? quantifier means "zero or one occurrence" of whatever comes before it, so it lets the regex accept entries with or without that leading character.

Here's the corrected pattern:

pattern = re.compile(r'[/*]?[AB]:{equipo}#?')

If you want to be extra clear (especially for readability later), you can wrap the optional part in a non-capturing group:

pattern = re.compile(r'(?:[/*])?[AB]:{equipo}#?')

Breaking Down the Corrected Regex

Let's break it down so you understand each piece:

  • [/*]?: Matches zero or one occurrence of / or * (so entries with or without this leading character are allowed)
  • [AB]: Matches either the letter A or B
  • :{equipo}: Matches your variable equipo (like P79COL01) preceded by a colon
  • #?: Matches zero or one # (handles cases where the # might be missing)

Example Usage

Let's test this with your sample string and equipo='P79COL01':

import re

equipo = 'P79COL01'
sample_string = "*B:P79COL01 # A:PED77MCY04 #"

# Corrected pattern
pattern = re.compile(r'[/*]?[AB]:{equipo}#?'.format(equipo=equipo))
matches = pattern.findall(sample_string)

print(matches)  # Output: ['*B:P79COL01 ']

If you swap equipo to 'PED77MCY04', it will match the A:PED77MCY04 part perfectly too.

Extra Tips for Beginners

  • Always use raw strings (r'') for regex patterns in Python—this avoids weird escape character issues that are easy to miss.
  • If you need to capture specific parts (like the leading *, the letter A/B, or the equipment code), wrap those sections in parentheses to create capture groups. For example:
    pattern = re.compile(r'([/*]?)([AB]):([A-Z0-9]+)#?')
    
    You can then extract each component using match.groups() after finding a match.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:53:37