java - How to test if a String contains both letter and number

前端 未结 7 1224
轻奢々
轻奢々 2020-12-16 01:07

I need a regex which will satisfy both conditions.

It should give me true only when a String contains both A-Z and 0-9.

Here\'s what I\'ve tried:

7条回答
  •  既然无缘
    2020-12-16 01:26

    This should solve your problem:

    ^([A-Z]+[0-9][A-Z0-9]*)|([0-9]+[A-Z][A-Z0-9]*)$
    

    But it's unreadable. I would suggest to first check input with "^[A-Z0-9]+$", then check with "[A-Z]" to ensure it contains at least one letter then check with "[0-9]" to ensure it contains at least one digit. This way you can add new restrictions easily and code will remain readable.

提交回复
热议问题