2

I'm using regex to validate if the value enter by user is a valid one.

string value = "500,21";
bool is_valid = Regex.IsMatch(value, "/^[0-9]+([,.][0-9]{2,2})?$/");

This piece of code should accept values like:

500.21
500,21

Yet it gives error saying that it ain't a valid value.

However, when using websites like https://www.regextester.com/ or https://regex101.com/ my regex works perfectly as you can see in here https://regex101.com/r/s6Cl9I/1

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Linesofcode
  • 5,327
  • 13
  • 62
  • 116

2 Answers2

2

Forward slashes are JavaScript's way of indicating the boundaries of a Regular Expression, much the same way that double-quotes indicate the boundaries of a string. For example, the following two expressions in JavaScript are equivalent:

/^[0-9]+([,.][0-9]{2,2})?$/.test("500,21")

new RegExp("^[0-9]+([,.][0-9]{2,2})?$").test("500,21")

Online Regex testers will often add those forward-slashes for you because they're thinking in a JavaScript context. But they're not actually part of the Regular Expression itself.

In C#, you're passing the regular expression as a string, so those slashes aren't necessary.

string value = "500,21";
bool is_valid = Regex.IsMatch(value, "^[0-9]+([,.][0-9]{2,2})?$");
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
0

C# does not like the /'s at the beginning and end of your expression. Regex engines can have different formats and special characters, so watch out for that!

zambonee
  • 1,599
  • 11
  • 17