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

如何使用Python re模块提取含/或|分隔的特定格式字符串?

正则匹配统一分隔符的卡号格式问题

问题场景

原代码可正确匹配以/分隔的卡号格式:

import re

cc = 'test 5555555555555555/03/22/284 test'

cc = re.findall('[0-9]{15,16}\/[0-9]{2,4}\/[0-9]{2,4}\/[0-9]{3,4}', cc)

print(cc)

运行输出:

['5555555555555555/03/22/284']

但当目标字符串为5555555555555555|03|22|284时,正则无法匹配,输出结果为[]。

需要实现一个正则规则,自动识别字符串中的分隔符(/或|),提取对应格式的完整内容——即含|时提取5555555555555555|03|22|284,含/时提取5555555555555555/03/22/284。

解决方案

利用正则的捕获组+反向引用特性,确保整个匹配串使用统一的分隔符,实现代码如下:

方法1:直接提取完整匹配结果

import re

# 测试不同场景
test_strings = [
    'test 5555555555555555/03/22/284 test',
    'test 5555555555555555|03|22|284 test',
    'mixed 5555555555555555/03|22/284 test'  # 混合分隔符,不匹配
]

# 正则规则:捕获分隔符后,用反向引用确保后续分隔符一致
pattern = r'\d{15,16}([\/\|])\d{2,4}\1\d{2,4}\1\d{3,4}'

for s in test_strings:
    match_result = re.search(pattern, s)
    if match_result:
        print(f"匹配成功:{match_result.group()}")
    else:
        print(f"无匹配:{s}")

运行输出:

匹配成功:5555555555555555/03/22/284
匹配成功:5555555555555555|03|22|284
无匹配:mixed 5555555555555555/03|22/284 test

方法2:用findall提取并拼接结果

如果需要使用findall,可通过分组拼接得到完整串:

import re

pattern = r'(\d{15,16})([\/\|])(\d{2,4})\2(\d{2,4})\2(\d{3,4})'
result = re.findall(pattern, 'test 5555555555555555|03|22|284 test')
if result:
    full_match = ''.join(result[0])
    print(full_match)  # 输出 5555555555555555|03|22|284

正则规则解释

  • \d{15,16}:匹配15或16位数字的卡号主体
  • ([\/\|]):捕获分隔符/或|为第1组
  • \1:反向引用第1组的分隔符,确保后续的分隔符与第一个完全一致
  • \d{2,4}、\d{3,4}:匹配对应位数的后续数字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:05:20