简体   繁体   中英

C#: Change NumberDecimalSeparator for Regex

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM