hacker tom
hacker tom

Reputation: 107

Regular expression detect that string contains both letters and numbers

Regular expression detect only letters+numbers not only numbers not only numbers

^(.*?(\b([A-Z]{2})([0-9]{7})\b)[^$]*)$

For example:

AB1234567 true
09AR30253 true
123456789 false
0912345JL true
AABBCCAAA false

Upvotes: 2

Views: 3136

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

To match 9 char strings that contain 2 consecutive letters and the rest is just digits, you may use

/^(?=.{9}$)\d*[a-zA-Z]{2}\d*$/

See the regex demo.

Details:

  • ^ - start of string
  • (?=.{9}$) - the string length must be 9 chars
  • \d* - zero or more digits
  • [a-zA-Z]{2} - 2 letters
  • \d* - zero or more digits
  • $ - end of string.

JS demo:

var strs = ['AB1234567', '09AR30253', '0912345JL', '123456789', 'AABBCCAAA'];
var rx = /^(?=.{9}$)\d*[a-zA-Z]{2}\d*$/;
for (var s of strs) {
  console.log(s, "=>", rx.test(s));
}

Upvotes: 3

Related Questions