Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a string containing as many digits as letters

Tags:

regex

I am trying to create a regex to match a string with the following criterion:

  1. the string must contain an even number of chars
  2. the string must contain as many digits as letters

Should match:

  • A3D4
  • A34DF5
  • 22FF

I tried, but didn't get a solution. Can you help me out?

like image 690
Ranjith Avatar asked Dec 06 '25 17:12

Ranjith


2 Answers

If the programming language you're using supports regex subroutines, then the following one should suit your needs:

^([A-Z](?1)*[0-9]|[0-9](?1)*[A-Z])+$

Regular expression visualization

Visualization by Debuggex

Demo on regex101

like image 172
sp00m Avatar answered Dec 08 '25 09:12

sp00m


using regexp to keep only letters or only numbers and comparing them : (example in javascript)

var str = 'A34DF5';
var result = str.replace(/[^a-z]/gi,'').length == str.replace(/[^0-9]/gi,'').length ;
like image 29
Sly Avatar answered Dec 08 '25 09:12

Sly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!