Python 3正则表达式问题:如何匹配仅含1个'b'的目标字符串?
Let's break down why your current regex is failing and how to fix it.
The Problem with Your Current Regex
Your regex a+bc* works for your valid examples, but it doesn't account for the entire string—it only checks if the string starts with a pattern that fits. When you test 'abb', match() finds the initial 'ab' (which matches a+bc* since c* allows zero c's) and returns a match, even though there's an extra 'b' at the end.
Solution 1: Enforce Order (A's → B → C's)
If your requirement is that the string must follow the sequence: one or more as → exactly one b → zero or more cs (no extra characters or bs), add start (^) and end ($) anchors to ensure the entire string is matched:
import re qq = re.compile('^a+bc*$') if qq.match('abb') is not None: print("True") else: print('False') # This will now output False as expected
This regex:
^anchors to the start of the stringa+matches one or moreasbmatches exactly onebc*matches zero or morecs$anchors to the end of the string, ensuring no extra characters (like an extrab) are present
Solution 2: Allow A's and C's Anywhere
If you want to allow as and cs to appear anywhere in the string (as long as there's exactly one b and at least one a), use this regex with a positive lookahead:
import re qq = re.compile('^(?=.*a)[ac]*b[ac]*$') if qq.match('abb') is not None: print("True") else: print('False') # Outputs False
Let's break this down:
^and$ensure the entire string is checked(?=.*a)is a positive lookahead that guarantees at least oneaexists in the string[ac]*matches zero or moreas orcs before thebbmatches the single requiredb[ac]*matches zero or moreas orcs after theb
This version will match valid strings like 'acb' or 'bac' while still rejecting strings with multiple bs.
内容的提问来源于stack exchange,提问作者Omar

