Home Reverse combination issue with Regex
Reply: 1

Reverse combination issue with Regex

kbvishnu Published in 2018-02-14 10:58:13Z

I am working on a validation issue using Regex.The below regex will accepts only data starts with HN or MY , followed by 8 digits. But it also accepts the NH or YM combinations too. How to prevent that ?

Regex reg; reg = new Regex(@"^[HN|hn]{2}|[MY|my]{2}[0-9]{8}");

Condition - Total Length 10 (2 characters + 8 digits) - Starts with HN or hn or MY or my

I am able to achieve partially, but this regex allows when the data will come in NH11111111 (N and H is allowed as the first two chars and followed by eight 1). Is there any possible to change the regex, so that it should accept only hn,hN,Hn,HN,my,mY,My,MY and not NH,YM (reverse combinations)

Valid Strings

  • HN11111111
  • MY11111111
  • hn23456789
  • my23456789
  • hN23456789
  • My23456789

Invalid Strings

  • HY11111111
  • HM11111111
  • HM111111
  • NH11111111
  • YM11111111 (Currently last and second last are allowed).

Thanks in advance(I am using .NET 4.5).

Wiktor Stribi┼╝ew
Wiktor Stribi┼╝ew Reply to 2018-02-14 11:59:47Z

Your regex, ^[HN|hn]{2}|[MY|my]{2}[0-9]{8}, is "corrupt" because of two things at least:

  • The | alternation operator without a grouping construct "splits" the pattern into two alternatives, one (^[HN|hn]{2}) matches H, h, N,nor|twice at the start of the string (and it can be followed with anything), and the[MY|my]{2}[0-9]{8}part matchesM,m,Y,yor|` twice and then any 8 digits anywhere inside the string (see this regex demo)
  • The [HN|hn] matches a single char because [...] define a character class, not a group of alternative patterns. You need to use round brackets, (...) (capturing) or (?:...) (non-capturing).

You may use

var rx = new Regex(@"^(?:HN|hn|MY|my)[0-9]{8}$");

See this regex demo


  • ^ - start of string
  • (?:HN|hn|MY|my) - HN, MY, hn, my substring
  • [0-9]{8} - 8 digits
  • $ - end of string.
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299514 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO