Python如何按字符串%前缀后的标注数值提取指定数量的后续字符
你之前的写法会匹配字符串中所有独立数字段,自然会拿到后续字符里的数字,核心解决思路是把数字的匹配范围限定在%后紧邻的位置即可,下面给两种Python实现方案:
方案1:正则匹配(写法简洁)
用re.search匹配%后紧跟的连续数字,避免匹配到后续内容里的数字:
import re def extract_target(s: str) -> str: # 仅匹配%后紧邻的连续数字,捕获组存储数字字符串 num_match = re.search(r'%(\d+)', s) if not num_match: return "" # 无匹配时的返回值可按需调整 count = int(num_match.group(1)) # 数字段结束的位置,从该位置往后取count个字符 start_extract_pos = num_match.end() return s[start_extract_pos: start_extract_pos + count]
测试效果:
- 输入
"%2ABCDE"→ 输出"AB" - 输入
"%12ABCDERTYUIOPLKHGF"→ 输出前12个后续字符 - 输入
"%2ABCD1"→ 输出"AB",不会误取后面的数字1
方案2:纯字符串处理(无需依赖正则库)
如果不想用正则,也可以直接遍历字符串提取数字:
def extract_target(s: str) -> str: percent_pos = s.find('%') if percent_pos == -1: return "" # 提取%后连续的数字段 num_str = "" current_pos = percent_pos + 1 while current_pos < len(s) and s[current_pos].isdigit(): num_str += s[current_pos] current_pos += 1 if not num_str: return "" count = int(num_str) return s[current_pos: current_pos + count]
内容的提问来源于stack exchange,提问作者user892077
相关产品推荐
相关产品推荐

