0

I want to make a regex that must have atlease one number and one alphabet.

onlyText will not math. But onlyText123 matches.

Tahir
  • 3,344
  • 14
  • 51
  • 69

2 Answers2

3

Here you go

^(?=.*[a-zA-Z])(?=.*[\d]).*$

The key is to use a technique called lookaround

buckley
  • 13,690
  • 3
  • 53
  • 61
0

You can try something like this

String p= "\\w*([a-zA-Z]\\d|\\d[a-zA-Z])\\w*";

System.out.println("1a".matches(p));//true
System.out.println("a1".matches(p));//true
System.out.println("1".matches(p));//false
System.out.println("a".matches(p));//false

([a-zA-Z]\\d|\\d[a-zA-Z]) == letter then number OR number then letter

and before and after it can (but don't have to) be letters and digits (\\w)

Pshemo
  • 122,468
  • 25
  • 185
  • 269