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

前端 未结 7 1230
轻奢々
轻奢々 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:24

    I suspect that the regex below is slowed down by the look-around, but it should work regardless:

    .matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")
    

    The regex asserts that there is an uppercase alphabetical character (?=.*[A-Z]) somewhere in the string, and asserts that there is a digit (?=.*[0-9]) somewhere in the string, and then it checks whether everything is either alphabetical character or digit.

提交回复
热议问题