Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Regex, how can I check that a regex group contains only digits

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading