Home > Software design >  Regex to match only 6letter alphanumeric words in a string
Regex to match only 6letter alphanumeric words in a string

Time:08-10

I am trying to match the 6 character word that has a combination of ONLY alphanumeric.

Example String:

Bus Express Wash at bay no 083457 - Truckno AB96CD & Truck no 12367S & 12368S

I am currently trying regex [a-zA-Z0-9]{6}

However, it matches below Output:

xpress
083457
ruckno
AB96CD
12367S
12368S

But, what I need is only combination of alphanumeric. Something like below Desired Output

AB96CD
12367S
12368S

CodePudding user response:

You may use this regex with 2 lookahead conditions:

\b(?=[a-zA-Z]*\d)(?=\d*[a-zA-Z])[a-zA-Z\d]{6}\b

RegEx Demo

RegEx Details:

  • \b: Word boundary
  • (?=[a-zA-Z]*\d): Lookahead to assert that we have at least one digit after 0 or more letters
  • (?=\d*[a-zA-Z]): Lookahead to assert that we have at least one letter after 0 or more digits
  • [a-zA-Z\d]{6}: Match 6 alphanumeric characters
  • \b: Word boundary
  • Related