Skip to content
Advertisement

Regex to match only 6letter alphanumeric words in a string

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

Advertisement

Answer

You may use this regex with 2 lookahead conditions:

b(?=[a-zA-Z]*d)(?=d*[a-zA-Z])[a-zA-Zd]{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-Zd]{6}: Match 6 alphanumeric characters
  • b: Word boundary
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement