Reputation: 25
I am trying to create regular expression for following type of strings:
combination of the prefix (XI/ YV/ XD/ YQ/ XZ), numerical digits only, and either no ‘Z’ or a ‘Z’ suffix.
For example, XD35Z
should pass but XD01HW
should not pass.
So far I tried following:
@"XD\d+Z?"
- XD35Z
passes but unfortunately it also works for XD01HW
@"XD\d+$Z"
- XD01HW
fails which is what I want but XD35Z
also fails
I have also tried @"XD\d{1,}Z"?
but it did not work
I need a single regex which will give me appropriate results for both types of strings.
Upvotes: 0
Views: 97
Reputation: 1542
You're misusing the $
which represents the end of the string in the Regex
It should be : @"^XD\d+Z?$"
(notice that it appears at the end of the Regex, after the Z?
)
Upvotes: 0
Reputation: 468
The regex following the behaviour you want is:
^(XI|YV|XD|YQ|XZ)\d+Z?$
Explanation:
combination of the prefix (XI/ YV/ XD/ YQ/ XZ)
^(XI|YV|XD|YQ|XZ)
numerical digits only
\d+
‘Z’ or a ‘Z’ suffix
Z?$
Upvotes: 0
Reputation: 6486
Try this regex:
^(XI|YV|XD|YQ|XZ){1}\d+Z{0,1}$
I'm using quantifying braces to explicitly limit the allowed numbers of each character/group. And the ^
and $
anchors make sure that the regex matches only the whole line (string).
Broken into logical pieces this regex checks
^(XI|YV|XD|YQ|XZ){1}
Starts with exactly one of the allowed prefixes \d+
Is follow by one or more digitsZ{0,1}$
Ends with between 0 and 1 Z
Upvotes: 1