开发者

Need a regex that validates a string with varying size

I need regex that validates a string that:

  • has 4 or 5 letters
  • then o开发者_StackOverflow社区ne underscore
  • then either an I or O (only one of them)
  • then one underscore
  • then 4 numeric digits

Now here where it complicates further. After all that it may have:

  • another underscore
  • then 4 numeric digits.

In the end all these must be valid:

ASDF_I_0002

ASDFG_O_0003_0324

ASDF_O_0001

ASDF_I_0001_0001

Thank you.


  • has 4 or 5 letters (A-Z)

    [A-Z]{4,5}
    
  • then one underscore

    [A-Z]{4,5}_
    
  • then either an I or O (only one of them)

    [A-Z]{4,5}_[IO]
    
  • then one underscore

    [A-Z]{4,5}_[IO]_
    
  • then 4 numeric digits

    [A-Z]{4,5}_[IO]_[0-9]{4}
    

After all that it may have:

    [A-Z]{4,5}_[IO]_[0-9]{4}()?
  • another underscore

    [A-Z]{4,5}_[IO]_[0-9]{4}(_)?
    
  • then 4 numeric digits.

    [A-Z]{4,5}_[IO]_[0-9]{4}(_[0-9]{4})?
    

You've lined out your requirements so nicely, I wonder where the problem was to make a regex from them. ;)


Try this one

^\w{4,5}_(I|O)_\d{4}(_\d{4})?$

EDIT: Compared to other solutions it evaluates ;-)

^\w{4,5}_[IO](_\d{4}){1,2}$


has 4 or 5 letters

  • \w{4-5}

then one underscore

  • _

then either an I or O (only one of them)

  • [IO]

then one underscore

  • _

then 4 numeric digits

  • \d{4}

Put it all together

\w{4-5}_[IO]_\d{4}

Although to match all your test cases you need to extend this

\w{4-5}_[IO](_\d{4}){1,2}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜