[英]Regex query to validate a currency string C#?
I am in no way a master of Regex
which is why I am here I currently have this:我绝不是正则
Regex
的大师,这就是我在这里的原因我目前有这个:
\s?[^0-9]?\s?[0-9,]+([\\.]{1})?[0-9]+\s?
To explain my validation attempt I am trying to validate that a string matches the correct formatting structure.为了解释我的验证尝试,我试图验证一个字符串是否匹配正确的格式结构。
I only want to match strings such as:我只想匹配字符串,例如:
- £1.00
1.00 英镑
- £10.00
10.00 英镑
- £100.00
100.00 英镑
- £1000.00
1000.00 英镑
- £10,000.00
10,000.00 英镑
- £100,000.00
100,000.00 英镑
- £1,234,546.00
1,234,546.00 英镑
Validation rules :验证规则:
For example, strings that shouldn't be accepted:例如,不应接受的字符串:
- £1
1英镑
- £10.000
10.000 英镑
- £1,00.00
£1,00.00
- £1,000.00
1,000.00 英镑
- 10,000.00
10,000.00
- £100,000,00
100,000,00 英镑
- £1.234.546
1.234.546 英镑
Really hoping that one of you amazing people can help me out, if you need anymore info then please let me know!真的希望你们中的一个了不起的人可以帮助我,如果您需要更多信息,请告诉我!
What about this?那这个呢?
new Regex(@"£\d{1,3}(\,\d{3})*\.\d{2}\b");
Edit:编辑:
new Regex(@"£((\d{1,4})|(\d{2,3}(\,\d{3})+)|(\d(\,\d{3}){2,}))\.\d{2}\b");
https://regex101.com/r/zSRw2B/1 https://regex101.com/r/zSRw2B/1
You can try the pattern below :您可以尝试以下模式:
^£(?:[0-9]{1,4}|[0-9]{2,3},[0-9]{3}|[0-9]{1,3}(?:,[0-9]{3}){2,})\.[0-9]{2}$
When pences are mandatory - \.[0-9]{2}
we have 3 options for pounds:当便士是强制性的 -
\.[0-9]{2}
我们有3 个英镑选项:
[0-9]{1,4} for sums in range £0 .. £9999
[0-9]{2,3},[0-9]{3} for sums in range £10,000 .. £999,999
[0-9]{1,3}(?:,[0-9]{3}){2,} for huge sums £1,000,000 ..
Demo:演示:
using System.Linq;
using System.Text.RegularExpressions;
...
Regex regex = new Regex(
@"^£(?:[0-9]{1,4}|[0-9]{2,3},[0-9]{3}|[0-9]{1,3}(?:,[0-9]{3}){2,})\.[0-9]{2}$";
string[] tests = new string[] {
"£1.00",
"£10.00",
"£100.00",
"£1000.00",
"£10,000.00",
"£100,000.00",
"£1,234,546.00",
"£1",
"£10.000",
"£1,00.00",
"£1,000.00",
"10,000.00",
"£100,000,00",
"£1.234.546",
};
string report = string.Join(Environment.NewLine, tests
.Select(test => $"{test,15} : {(regex.IsMatch(test) ? "Match" : "Fail")}"));
Console.Write(report);
Outcome:结果:
£1.00 : Match
£10.00 : Match
£100.00 : Match
£1000.00 : Match
£10,000.00 : Match
£100,000.00 : Match
£1,234,546.00 : Match
£1 : Fail
£10.000 : Fail
£1,00.00 : Fail
£1,000.00 : Fail
10,000.00 : Fail
£100,000,00 : Fail
£1.234.546 : Fail
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.