Reputation: 1983
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}))?
prefix
group is "retour-"
and if it occurs it is at the beginning.trackingNumber
group is mandatory and should consist only of digits.postfix
group is "-"
followed only by digits, it is not mandatory.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."1234ABC3456"
should not be a success"retour-123456-12B"
should also not be a successThe 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
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