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

如何编写可从字符串中提取百分比及百分比范围的正则表达式

正则匹配解决方案

你需要的正则表达式如下:

\b\d+(?:-\d+)?(?:%|percent\b)

正则拆解说明

  • \b:匹配单词边界,避免误匹配到嵌入在其他字符串中的数字
  • \d+:匹配整数格式的百分比数值
  • (?:-\d+)?:非捕获组,匹配范围格式的后半段数值,?标识该部分可选,同时兼容单个百分比和百分比范围两种格式
  • (?:%|percent\b):非捕获组,同时支持百分号%和英文percent两种百分比标识形式,末尾的\b避免匹配到percentage等以percent开头的长单词

适配小数百分比的版本

如果需要支持带小数的百分比(如23.5%、10.5-45.8%),可使用调整后的正则:

\b\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)?(?:%|percent\b)

匹配效果示例

测试字符串及匹配结果:

  • 输入:Adidas <strong>30-60%</strong> Off on footwear → 匹配结果:30-60%
  • 输入:The discount for this product is 56% → 匹配结果:56%
  • 输入:You can save 20-40 percent on home appliances → 匹配结果:20-40 percent
  • 输入:Cashback up to 15 percent for new users → 匹配结果:15 percent

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:06:06