ShalakaV
ShalakaV

Reputation: 25

Regular expression for specific combination of alphabets and numbers

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:

I need a single regex which will give me appropriate results for both types of strings.

Upvotes: 0

Views: 97

Answers (3)

Dean
Dean

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

Answers_Seeker
Answers_Seeker

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

ryanyuyu
ryanyuyu

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 digits
  • Z{0,1}$ Ends with between 0 and 1 Z

Upvotes: 1

Related Questions