简体   繁体   中英

Regex to match a string containing as many digits as letters

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?

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])+$

正则表达式可视化

Visualization by Debuggex

Demo on regex101

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM