-1

I need a regex in C# for below mentioned number

31–00–123456–000–0001

I am having a problem putting the dash in the regex. The number validation is pretty fine.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
ispostback
  • 330
  • 2
  • 7
  • 23
  • Please provide more information. Are there any other limitations to the string? Will each of those sets of digits always be their respective lengths? Are any of the values static? Do you have an example from which you've started? – rbonestell Feb 18 '20 at 06:46
  • 1
    `@"^[0-9]{2}–[0-9]{2}–[0-9]{6}–[0-9]{3}–[0-9]{4}$"`? – Dmitry Bychenko Feb 18 '20 at 06:50
  • 2
    That dash character is `U+02013`. Is that the only dash you expect, or is `U+0002D` also acceptable? Be very clear about what you want. And show your attempt. – madreflection Feb 18 '20 at 06:51

2 Answers2

0

Is this what you need?

(\d{2})[\–\-](\d{2})[\–\-](\d{6})[\–\-](\d{3})[\–\-](\d{4})

So, if you already have code extracted to string variable code and want to check that it matches then use ^ and $ like here:

^(\d{2})[\–\-](\d{2})[\–\-](\d{6})[\–\-](\d{3})[\–\-](\d{4})$

According to comments, its better to use [0-9] to reduce other types of degets.

^([0-9]{2})[\–\-]([0-9]{2})[\–\-]([0-9]{6})[\–\-]([0-9]{3})[\–\-]([0-9]{4})$
TemaTre
  • 1,422
  • 2
  • 12
  • 20
  • I suggest adding anchors: `^...$` or `bla-bla-bla_valid_ESI_number_bla-bla-bla` will match. Be carefult with `\d`: in .net it means *any unicode digit*, so `۱۳–۱۳–۱۳۱۳۱۳–۱۳۱–۱۳۱۳` (*persian digits*) would match - either switch to `[0-9]` or add `RegexOptions.ECMAScript` – Dmitry Bychenko Feb 18 '20 at 07:16
  • Thanks for comment. I change my answer. – TemaTre Feb 18 '20 at 07:35
0

If any kind of dash (e.g. U+02013) are acceptable, I suggest using \p{Pd} which means any unicode dash (Punctuation dash). In case the digits should be separated by any dash, which, however, must be the same within the entire string:

Regex regex = new Regex(@"^[0-9]{2}(\p{Pd})[0-9]{2}\1[0-9]{6}\1[0-9]{3}\1[0-9]{4}$");

Demo:

  string[] tests = new string[] {
    "31–00–123456–000–0001", // All Dashes
    "31-00-123456-000-0001", // All minuses
    "31–00-123456-000-0001", // Dash then minues
  };

  string report = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,25} :: {(regex.IsMatch(test) ? "Matched" : "Failed")}"));

  Console.Write(report);

Outcome:

31–00–123456–000–0001 :: Matched
31-00-123456-000-0001 :: Matched
31–00-123456-000-0001 :: Failed

If you want to tolerate diffrent dashes within the same string:

Regex regex = new Regex(
  @"^[0-9]{2}\p{Pd}[0-9]{2}\p{Pd}[0-9]{6}\p{Pd}[0-9]{3}\p{Pd}[0-9]{4}$");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215