C# 带正则表达式的折扣掩码
是否可以创建以%或数字作为折扣值的“动态”折扣掩码?做这件事的简单方法是什么? valide输入的样本:-25%或0.25或-5$不是0,点后两位数C# 带正则表达式的折扣掩码,c#,regex,C#,Regex,是否可以创建以%或数字作为折扣值的“动态”折扣掩码?做这件事的简单方法是什么? valide输入的样本:-25%或0.25或-5$不是0,点后两位数 @"(\+|-)?(\d+(\.\d*)?|\.\d+)%?" 它将发现: 123.23 12.4% .34 .34% 45. 45.% 8 7% 34 34% +2.55% -1.75% 。。。您还可以包括数千个分隔符 我必须承认,我的第二个正则表达式看起来像一只猫从我的键盘上经过。这是解释 (\+\124;-)?可选?加号或减号 \d+(,
@"(\+|-)?(\d+(\.\d*)?|\.\d+)%?"
它将发现:
123.23
12.4%
.34
.34%
45.
45.%
8
7%
34
34%
+2.55%
-1.75%
。。。您还可以包括数千个分隔符
我必须承认,我的第二个正则表达式看起来像一只猫从我的键盘上经过。这是解释
(\+\124;-)?
可选?
加号或减号
\d+(,\d{3})*(?!\d)(\.\d*)?
一个或多个数字\d+
后跟任意数量的数千个分隔符加上三个数字(,\d{3})*
,后面不跟任何数字(?!\d)
,以禁止按顺序排列四个数字,可以选择后跟一个小数点和任意数量的数字(\.\d*)?
\.\d+
或小数点后跟至少一位数字
%?
最后是一个可选的百分号。如果我没弄错你的问题,你想要这样的东西:
@"^[+-]?(?:\d*\.)?\d+[%$]?$"
这部分基于您的-5$
示例。但是,通常,$
会放在前面,因此您需要类似以下内容:
@"^(?:\$(?!.*%))?[+-]?(?:\d*\.)?\d+%?$"
这将允许$-5.00
、10
或+20%
,但会阻止$5%
编辑:
使用Olivier允许逗号的想法:
@"^(\$(?!.*%))?[+-]?(\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
我不知道你的意思。请阅读并相应修改您的问题。您所说的“动态”折扣面具是什么意思?您是否希望使用正则表达式匹配10%、15%、100%等?不仅仅是百分比((看一看编辑后的文本仍然不清楚。你所说的
动态
是什么意思?掩码?什么掩码?输出是什么?在什么背景下?为什么是正则表达式?你想实现什么?我可以看出你没有读到我发布的链接…不客气。另外,由于你是StackOverflow新手,我想通知你,你可以投票给answe然后通过勾选答案旁边的勾号来接受对你帮助最大的答案。在这个网站上,向上投票或接受答案都算作“谢谢”。那么-10怎么样?(减去10美元,而不是百分比)@curiousity:我在三分钟前加了(\+\124;-)?
。你的(,?\d)*
标记已关闭。这将允许123,4,5,6
。它还允许123.
,点后不带任何内容。我的目的是允许0.5
和1使用5
和1使用使用来解析用户输入。如果您正在解析用户输入,这可能是有意义的。我更正了数千个分隔符部分,使其更准确。第ousands分隔符现在看起来不错。问题是您的(\.\d*)
标记在句点之后不需要任何数字。您最好使用(\.\d+)
来代替。如果没有逗号,您可以对数字部分使用\d*(\.\d+)
,但我认为您仍然可以将其简化为\d{1,3}(,\d{3})*(\。\d+)\。\d+
更精确。
@"^ #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