如何编写匹配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 (so150.0%is okay, but150.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

