Python正则表达式匹配:兼容带*与不带*开头的目标内容
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 letterAorB:{equipo}: Matches your variableequipo(likeP79COL01) 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:
You can then extract each component usingpattern = re.compile(r'([/*]?)([AB]):([A-Z0-9]+)#?')match.groups()after finding a match.
内容的提问来源于stack exchange,提问作者Cesar Justo

