New Coder
New Coder

Reputation: 501

c# regular expression equivalent to js regular expression

Can someone tell me the regular expression equivalent to below javascript expression

var validformat = /^[-+]?\d*\.?\d*$/

I tried the same in my c# code using below but its failing.

Regex rgx = new Regex(@"/^[-+]?\d*\.?\d*$/")
bool result = rgx.IsMatch(expression)

The code is basically to validate the Number - it should allow 20,000 but not 20.3. and 20+3

Upvotes: 0

Views: 67

Answers (2)

merlin2011
merlin2011

Reputation: 75575

I think you need to get rid of / on both sides, as well as changing \. to something more specific. If you need more possible separators, just add them inside [+,]. You have currently only mentioned + and , in your question.

Updated the regex to remove matching of 20+3.

using System.Text.RegularExpressions;
using System;

public class Program{
    public static void Main(string[] args) {
        Regex rgx = new Regex(@"^[-+]?\d*,?\d+$");
        Console.WriteLine(rgx.IsMatch("10000"));  //True
        Console.WriteLine(rgx.IsMatch("20,000")); //True
        Console.WriteLine(rgx.IsMatch("20+100")); // False
        Console.WriteLine(rgx.IsMatch("20000,")); // False
        Console.WriteLine(rgx.IsMatch("20.200")); // False
    }
}

Upvotes: 1

aelor
aelor

Reputation: 11116

better use this regex:

^\d*[-+,]?\d*$

use it like this in your code :

http://ideone.com/HIgMzp

it will match 20,000 and 20+3 but will not match 20.3 or 100.1

Match match = Regex.Match(input, @"^\d*[-+,]?\d*$")

Upvotes: 0

Related Questions