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

如何从指定格式字符串中提取line_items_attributes后的数字?

提取line_items_attributes后的目标数字

嘿,我来帮你搞定这个问题!你需要从固定格式的字符串里精准提取line_items_attributes后面的数字,不管前面orders_attributes后的动态数字怎么变,对吧?

核心思路

我们可以用正则表达式精准定位目标位置:直接匹配line_items_attributes[这个固定文本段,然后捕获它后面括号里的数字——这个数字的位置是固定跟在line_items_attributes之后的,完全不受前面动态数字的干扰。

具体实现

这里给出适配你需求的正则表达式,它能匹配0到9999999999999之间的任意长度数字:

line_items_attributes\[(\d+)\]
  • line_items_attributes\[:匹配固定的文本部分(注意[在正则里是特殊字符,需要用\转义)
  • (\d+):捕获一个或多个数字(\d代表数字,+表示匹配1次及以上,刚好覆盖你需要的数字长度范围)
  • \]:匹配闭合的括号(同样需要转义)

示例代码(JavaScript)

const inputStr = 'task[orders_attributes][4][line_items_attributes][2][id]';
const regex = /line_items_attributes\[(\d+)\]/;
const matchResult = inputStr.match(regex);

// 提取到的数字会在matchResult的第1个分组里
const targetNumber = matchResult ? matchResult[1] : null;
console.log(targetNumber); // 输出: "2"

示例代码(Python)

import re

input_str = 'task[orders_attributes][4][line_items_attributes][2][id]'
regex = r'line_items_attributes\[(\d+)\]'
match_result = re.search(regex, input_str)

target_number = match_result.group(1) if match_result else None
print(target_number) # 输出: "2"

为什么这个方法靠谱?

  • 完全忽略前面orders_attributes后的动态数字,直接锁定目标位置,不会因为前面数字的变化而匹配错误
  • \d+支持任意长度的数字,完美覆盖你要求的0到9999999999999范围
  • 正则逻辑简单清晰,容易理解和维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:05:34