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

如何编写正则表达式匹配符合特定规则的包裹重量数值?

正确正则表达式

匹配完整片段的正则如下,覆盖你要求的所有规则:

(must not exceed|cannot exceed|limited by)[^a-zA-Z]*([+-]?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?)[^a-zA-Z]*(kg|k\.g|k\/g)

如果需要直接提取数值,取上述正则的第二个捕获组即可,不需要二次处理匹配到的完整片段。


各部分规则对应说明

  • 开头(must not exceed|cannot exceed|limited by):完全匹配你指定的三个起始短语
  • [^a-zA-Z]*:匹配0到任意长度的非字母字符,不会误吞字母内容,符合中间间隔规则
  • 数值部分[+-]?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?:支持可选正负号、带千分位逗号的整数、普通整数、可选小数部分,覆盖你给出的所有数值格式
  • 末尾(kg|k\.g|k\/g):完全匹配你指定的三个单位格式

测试用例匹配结果

对你提供的测试用例匹配情况如下:

  • 字符串:The 3 boxes with red on them must not exceed -23.4435kg and don't pick them up.
    匹配片段:must not exceed -23.4435kg,提取数值:-23.4435
  • 字符串:Parcels that can be sent are limited by 1,402kg and its okay to send
    匹配片段:limited by 1,402kg,提取数值:1,402
  • 字符串:The 2 boxes on the shelf must not exceed: 102 kg
    匹配片段:must not exceed: 102 kg,提取数值:102
  • 字符串:Do not pick up 18 boxes at a time and make sure they cannot exceed,: 92302 k.g
    匹配片段:cannot exceed,: 92302 k.g,提取数值:92302
  • 字符串:Do not pick up boxes that weight 56.23 kg
    无匹配:符合规则,该字符串不存在指定的起始短语
  • 字符串:Boxes cannot exceed -23 k/g
    匹配片段:cannot exceed -23 k/g,提取数值:-23

注意事项

如果你使用的正则引擎默认不支持跨行匹配,添加s单行匹配标志即可,[^a-zA-Z]本身包含换行符、空格、标点等所有非字母字符,支持跨行匹配场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:36:04