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

如何编写匹配50%至150%数值的Regex正则表达式?

Got it, let's figure out how to write a regex that catches percentages between 50% and 150% (including both endpoints). I'll break this down step by step, covering whole numbers first, then extending to decimals if you need that.

Matching Whole Number Percentages

We can split the range into three distinct parts to cover every valid whole number case:

  • 50% to 99%: Two-digit numbers from 50 up to 99, followed by a % sign → [5-9][0-9]%
  • 100% to 149%: Three-digit numbers starting with 1, tens digit from 0-4, any units digit → 1[0-4][0-9]%
  • 150%: The exact upper limit, since it's a unique value → 150%

Combine these with the | (OR) operator, wrap them in a non-capturing group, and add word boundaries to avoid partial matches (like picking up 50% from 1500%):

\b(?:[5-9][0-9]%|1[0-4][0-9]%|150%)\b
  • \b = Word boundary: Ensures we don't match partial numbers embedded in longer strings.
  • (?:...) = Non-capturing group: Groups the patterns together without creating an unnecessary capture group.

Matching Percentages with Decimals

If you need to support values like 50.5% or 149.99%, we can adjust the regex to allow optional decimal parts. Here are two common scenarios:

Allow Any Number of Decimal Places

This works for values like 50.1%, 123.456%, and 150.0% (but blocks 150.1% since it's over the limit):

\b(?:[5-9][0-9](?:\.\d+)?%|1[0-4][0-9](?:\.\d+)?%|150(?:\.0+)?%)\b
  • (?:\.\d+)? = Optional decimal point followed by one or more digits.
  • For 150%, we use (?:\.0+)? to only allow trailing zeros (so 150.0% is okay, but 150.1% isn't).

Limit to 1-2 Decimal Places

If you want to restrict decimals to a reasonable number (like currency-style precision):

\b(?:[5-9][0-9](?:\.\d{1,2})?%|1[0-4][0-9](?:\.\d{1,2})?%|150(?:\.0{1,2})?%)\b
  • \d{1,2} = Matches 1 or 2 digits after the decimal point.

Quick Test Cases

  • ✅ Matches: 50%, 75%, 100%, 149%, 150%, 50.5%, 149.99%, 150.0%
  • ❌ Doesn't match: 49%, 151%, 200%, 500%, 150.1%

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:43:15