如何在货币验证正则表达式中加入百分比验证支持
Extending Gary's Regex to Support Currency, Numeric, and Percentage Inputs
Great question! Let's walk through adapting Gary's existing regex to handle percentage values while retaining full support for currency and numeric formats.
First, let's recap what Gary's original regex does:
(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$
It validates:
- Currency values with an optional leading
$, optional thousand separators, and up to 2 decimal places (e.g.,$1,234.56,$0.99) - Numeric values with optional thousand separators and up to 2 decimal places (e.g.,
123,45.67,1,000,000)
To add percentage support, we need to allow values that end with a % (and ensure we don't mix currency symbols with percentages). Here's the modified regex:
(?=.)^(?:\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?|(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?%)$
Key Changes Explained:
- We wrapped the original pattern in a non-capturing group
(?:...)and added a second branch with%at the end. This ensures:- The first branch handles currency/numeric inputs (no trailing
%) - The second branch handles percentage inputs (trailing
%, no leading$)
- The first branch handles currency/numeric inputs (no trailing
- The
(?=.)at the start ensures the input isn't empty (same as the original regex)
Valid Examples:
- Currency:
$1,234.56,$0.99,50,1000.50 - Numeric:
123,45.67,1,000,000,0.75 - Percentage:
5%,10.5%,1,234.56%,0.25%,100%
Invalid Examples (Rejected by the Regex):
- Mixed currency/percentage:
$100% - Leading percentage:
%100 - Invalid decimal formatting:
100.,12.345 - Malformed thousand separators:
1,2345,123,45
Optional Tweak: Allow Spaces Before %
If you want to permit inputs like 100 % (with a space before the percentage sign), modify the regex to include \s* before the %:
(?=.)^(?:\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?|(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?\s*%)$
内容的提问来源于stack exchange,提问作者Michael Shrader
相关产品推荐
相关产品推荐

