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

如何用Python正则表达式提取含可变前缀与yyyymmdd格式的字符串分段

正则表达式提取分段字段方案

核心正则表达式

^([A-Za-z]{2,3})(\d{4})(\d{2})(\d{2})$

规则解释

  • ^ 和 $:锚定字符串首尾,确保整个字符串完全匹配格式,避免部分匹配的情况
  • ([A-Za-z]{2,3}):捕获2-3个字母组成的name字段,括号用于标记捕获组
  • (\d{4}):捕获4位数字,对应year(yyyy格式)
  • (\d{2}):捕获2位数字,对应month
  • (\d{2}):捕获2位数字,对应day

提取示例(Python)

import re

# 定义正则模式
pattern = r'^([A-Za-z]{2,3})(\d{4})(\d{2})(\d{2})$'
# 测试案例
test_strings = ['FWI20010112', 'DC20030405']

for s in test_strings:
    match_result = re.match(pattern, s)
    if match_result:
        name = match_result.group(1)
        year = match_result.group(2)
        month = match_result.group(3)
        day = match_result.group(4)
        print(f"name: {name}, year: {year}, month: {month}, day: {day}")

执行输出:

name: FWI, year: 2001, month: 01, day: 12
name: DC, year: 2003, month: 04, day: 05

提取示例(JavaScript)

const regexPattern = /^([A-Za-z]{2,3})(\d{4})(\d{2})(\d{2})$/;
const testStrings = ['FWI20010112', 'DC20030405'];

testStrings.forEach(str => {
    const match = str.match(regexPattern);
    if (match) {
        const [_, name, year, month, day] = match;
        console.log(`name: ${name}, year: ${year}, month: ${month}, day: ${day}`);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:15:44