开发者

How to write regex pattern to match AAAA00000000-0000?

I need a regex to match 开发者_开发问答a string in any of these formats:

  1. "AAAA00000000"
  2. "AAAA00000000-0000"
  3. "0000000000"

I've got the first and third pattern right, this is what I came up with

^(([a-zA-Z]{4}[0-9]{8})|([0-9]{10}))$

I can't get that working to include the second pattern.


^[a-zA-Z]{4}[0-9]{8}(-[0-9]{4})?$

That is, XXXXnnnnnnnn and an optional -nnnn part.

  • XXXXnnnnnnnn
  • XXXXnnnnnnnn-nnnn

You can leave out the outermost parenthesis as this group equals the entire match (capturing group 0).

EDIT
Update to match nnnnnnnnnn, too:

^[0-9]{10}|[a-zA-Z]{4}[0-9]{8}(-[0-9]{4})?$

Matches:

  • nnnnnnnnnn
  • XXXXnnnnnnnn
  • XXXXnnnnnnnn-nnnn

EDIT #2
In response to comment, this is the shortest / most readable I'm able to cook up:

^[0-9]{10}|[a-zA-Z]{4}[0-9]{8}(-[0-9]{4}|)$

Same characteristics as immediately above.


You are missing the "-" of the second format...


^\w{4}\d{8}(-\d{4})?$

Fixed a typo


^[a-zA-Z]{4}([0-9]{8}|[0-9]{8}\-[0-9]{4})$
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜