0

I'm parsing decimal values with a decimal separator using regex, that are in US format, like: 2.56

But my system's culture decimal separator is set to a comma, so when I use the decimal class \d, the regex fails to recognize "2.56" as a valid decimal number.

I would like to stick to the \d for the sake of readability and simplicity. Can I force it to recognize dot as a decimal separator?

When using float.TryParse(), I can enforce it to use dot as a decimal separator:

var usCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
float.TryParse(text, System.Globalization.NumberStyles.Number, usCulture, out s )

Can I do something similar for regex?

I tried changing current thread's culture:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

but it doesn't seem to affect the regex, it still expects comma as a decimal separator.

Yekoor
  • 79
  • 3

2 Answers2

1

I would like to stick to the \d for the sake of readability and simplicity. Can I force it to recognize dot as a decimal separator?

No, that is because \d is shorthand for [0-9]. It doesn't match for anything else, including separators.

If you want to match decimals, you need something like this:

-?\d+(\.\d+)?

Demo

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

Well, \d is a any unicode digit, not a floating point number. If you insist on Regular Expressions you have to construct pattern manually; in the simplest case (no exponential part, no thousand separator, arbitrary length etc.) it can be

  string escapedSeparator = Regex.Escape(
    CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

  string pattern = $"^-?[0-9]+({escapedSeparator}[0-9]+)?$";

  if (Regex.IsMatch("-123.456", pattern)) {
    ...
  }

I really doubt if it's better than double.TryParse(...) which has been specially designed for this purpose.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215