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

如何提取固定结构字符串中Customer后的数字?求更优方案

提取固定格式字符串中"Customer"后的数字的最优方法

先看你给出的示例字符串:

Herr Max Mustermann Musterstraße 3 12345 City Customer 123456 Date 03.01.2023

你的思路完全可行,但还有更简洁高效的实现方式——直接用正则表达式一步完成匹配提取,无需分割数组再遍历:

以PHP为例,代码示例:

$str = 'Herr Max Mustermann Musterstraße 3 12345 City Customer 123456 Date 03.01.2023';
preg_match('/Customer (\d+)/', $str, $matches);
$customerNumber = $matches[1]; // 最终结果为123456

该方法的优势

  • 代码更简洁:省去循环判断的冗余逻辑,一行匹配就能拿到目标值
  • 效率更高:无需将整个字符串分割为数组再遍历,正则引擎直接定位目标内容
  • 适配性强:只要"Customer"和后续数字以空格分隔,无论前后内容如何变化,都能稳定提取

如果是Python,实现思路一致:

import re
str_content = 'Herr Max Mustermann Musterstraße 3 12345 City Customer 123456 Date 03.01.2023'
match_result = re.search(r'Customer (\d+)', str_content)
customer_number = match_result.group(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:42:37