Home > Software engineering >  C# Regex, how can I check that a regex group contains only digits
C# Regex, how can I check that a regex group contains only digits

Time:08-22

I made the following regex pattern in C#:

Regex pattern = new Regex(@"(?<prefix>retour-)?(?<trackingNumber>\s*[0-9] \s*)(?<postfix>-([0]|[1-9]{1,2}))?");
(?<prefix>retour-)?(?<trackingNumber>\s*[0-9] \s*)(?<postfix>-([0]|[1-9]{1,2}))?
  • This is what I want: Three groups.
    • The prefix group is "retour-" and if it occurs it is at the beginning.
    • The trackingNumber group is mandatory and should consist only of digits.
    • The postfix group is "-" followed only by digits, it is not mandatory.
  • I want the trackingNumber group to be a success only if it contains numbers. The same goes for the postfix. In a similar question, the problem was solved by using regex anchors (^, $) but in my case I cannot use them because the trackingNumber group starts in the middle.

For example:

  • "1234ABC3456" should not be a success
  • "retour-123456-12B" should also not be a success

The problem is that the regex (?<trackingNumber>\s*[0-9] \s*) will return a success even for a series that does not contain only digit numbers.

CodePudding user response:

This pattern works for me:

^(?<prefix>retour-)?\s*(?<trackingNumber>\d )\s*(?<postfix>-(\d ))?$
Input Result
1234ABC3456 No match
retour-123456-12B No match
retour-123456-123 prefix: "retour-", trackingNumber: "123456", postFix: "-123"
543210-999 trackingNumber: "543210", postFix: "-999"
987654 trackingNumber: "987654"

https://regex101.com/r/Fo1pvU/1

  • Related