简体   繁体   中英

JavaScript regex to split numbers and letters

I need regex pattern to split a string into numbers and letters. Ie .1abc2.5efg3mno should be split into [".1","abc","2.5","efg","3","mno"] .

The current regex I tried is:

var str = ".1abc2.5efg3mno";
regexStr= str.match(/[a-zA-Z]+|[0-9]+(?:\.[0-9]+|)/g);

Output obtained is:

["1","abc","2.5","efg","3","mno"]

The number .1 is taken as 1 whereas I need it as .1 .

If it's a matter of separating letters from non-letters, then the regex can be made quite simple:

 var str = ".1abc2.5efg3mno"; var regexStr = str.match(/[az]+|[^az]+/gi); console.log(regexStr); 

Ie match a group of letters or a group of non-letters.

 var z = ".1abc2.5efg3mno".match(/[\\d\\.]+|\\D+/g); console.log(z); 

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