如何从输入字符串中匹配提取以三个连续大写字母开头的目标字符串
匹配三个连续大写字母开头字符串的实现方案
核心使用正则表达式完成匹配,通用匹配规则为:\b[A-Z]{3}[A-Za-z0-9]*\b
规则说明:
\b匹配单词边界,避免匹配到单词中间出现三个大写字母的无效内容[A-Z]{3}精准匹配连续3个大写英文字母[A-Za-z0-9]*匹配三个大写字母后续的所有字母、数字字符,可根据实际需求调整匹配范围(例如仅需后续为数字时可修改为[0-9]*)
Python 实现代码
import re input_content = "Can I have the Outstanding amount for MEXB18342700?" match_rule = r"\b[A-Z]{3}[A-Za-z0-9]*\b" result = re.search(match_rule, input_content) if result: VAR = result.group() print(f"VAR = {VAR}")
运行输出结果:VAR = MEXB18342700
JavaScript 实现代码
const inputContent = "Can I have the Outstanding amount for MEXB18342700?" const matchRule = /\b[A-Z]{3}[A-Za-z0-9]*\b/ const result = inputContent.match(matchRule) if (result) { const VAR = result[0] console.log(`VAR = ${VAR}`) }
特殊场景调整说明
如果需要校验整个输入字符串完全符合「三个大写字母开头」的规则,可将正则规则修改为:^[A-Z]{3}[A-Za-z0-9]*$,其中^表示字符串开头,$表示字符串结尾。
内容的提问来源于stack exchange,提问作者Gabriel Rosa
相关产品推荐
相关产品推荐

