Regex matches a string containing as many numbers as letters

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

  • the string must contain an even number of characters
  • the string must contain as many numbers as letters

Should match:

  • A3D4
  • A34DF5
  • 22FF

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

+3


source to share


2 answers


If the programming language you are using supports regular expression routines , then the following should suit your needs:

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

      

Regular expression visualization



visualization Debuggex

Demo on regex101

+3


source


using regexp to store only letters or just numbers and compare them: (example in javascript)



var str = 'A34DF5';
var result = str.replace(/[^a-z]/gi,'').length == str.replace(/[^0-9]/gi,'').length ;

      

+1


source







All Articles