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,194
  • 12
  • 50
  • 67

2 Answers2

3

Here you go

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

The key is to use a technique called lookaround

buckley
  • 12,834
  • 2
  • 47
  • 56
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
  • 118,400
  • 24
  • 176
  • 257