Click here to Skip to main content
14,733,333 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

What's the best Regex for .NET for the following number:

1. Show $ currency symbol
2. Mminimum number of 2000
3. Maximum number is 1000000
4. No decimal places
5. Comma is not needed


Thanks,
Jassim

What I have tried:

^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$
Posted
Updated 19-Feb-20 15:19pm

To be honest, I wouldn't use a Regex - I'd use TryParse:
NumberStyles styles = NumberStyles.Integer | NmberStyles.AllowCurrencySymbol;
CultureInfo provider = new CultureInfo("en-US");
if (int.TryParse(stringToConvert, styles, provider, out number))
    {
    if (number >= 2000 && number <= 1000000)
        {
        ...
   
While it's theoretically possible to match min and max values with regex, you'd have to do
100|101|102|103...
all the way through your range (there are some shorter ways but it's hard for humans to compute them)

I agree with OriginalGriff

This is easier with TryParse/Parse
   
Quote:
What's the best Regex for .NET for the following number

I would use Regex to match the pattern, then check the value in code.
^\$(\d{1,3}(\,?\d{3}){1,2})$

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900