Devid
Devid

Reputation: 1983

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}))?

For example:

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.

Upvotes: 2

Views: 65

Answers (1)

Dai
Dai

Reputation: 155125

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

Upvotes: 4

Related Questions