带有正则表达式的折扣面具
本文关键字:面具 正则表达式 | 更新日期: 2023-09-27 18:36:02
是否可以创建一个将%或数字作为折扣值的'动态'折扣掩码?最简单的方法是什么? 有效输入的样本:-25% 或 0.25 或 -5$ 不是 0 和点后两位数
尝试
@"('+|-)?('d+('.'d*)?|'.'d+)%?"
它将发现:
123.2312.4%.34.34%45.45.%87%3434%+2.55%-1.75%
更新
并...
@"('+|-)?('d+(,'d{3})*(?!'d)('.'d*)?|'.'d+)%?"
。您还可以包含数千个分隔符。
我必须承认,我的第二个正则表达式看起来像一只猫走过我的键盘。这里的解释
('+|-)?
可以选择?
加号或减号。
'd+(,'d{3})*(?!'d)('.'d*)?
一个或多个数字'd+
后跟任意数量的千位分隔符加上三位数字(,'d{3})*
,不后跟任何数字(?!'d)
,以便不允许按顺序使用四位数字,可以选择后跟小数点和任意数量的数字('.'d*)?
。
|'.'d+
或小数点后跟至少一位数字。
%?
终于有一个可选的百分号。
如果我
理解你的问题没错,你想要这样的东西:
@"^[+-]?(?:'d*'.)?'d+[%$]?$"
这部分是基于您的-5$
示例。不过,通常情况下,$
会排在前面,所以你需要这样的东西:
@"^(?:'$(?!.*%))?[+-]?(?:'d*'.)?'d+%?$"
这将允许$-5.00
、10
或+20%
,但阻止$5%
。
编辑:
按照奥利维尔允许逗号的想法运行:
@"^('$(?!.*%))?[+-]?('d{1,3}((,'d{3})*|'d*))?('.'d+)?'b%?$"
扩展以使其更易于理解:
@"^ #Require matching from the beginning of the line
('$(?!.*%))? #Optionally allow a $ here, but only if there's no % later on.
[+-]? #Optionally allow + or - at the beginning
(
'd{1,3} #Covers the first three numerals
((,'d{3})*|'d*) #Allow numbers in 1,234,567 format, or simply a long string of numerals with no commas
)? #Allow for a decimal with no leading digits
('.'d+)? #Optionally allow a period, but only with numerals behind it
'b #Word break (a sneaky way to require at least one numeral before this position, thus preventing an empty string)
%? #Optionally allow %
$" #End of line