简体   繁体   中英

Match all character before numbers

I want to do operations with the numbers in a string, but the operation depends on the char before that number, so I need to get the char before any number in a string. Note that the char before a number could be another number.

So far I've done /(.)[0-9]/g , but this is not matching the case where there's a number before another number. For example:

positions: 0123456789012
string:    a a4 bb4 c44c

matches:

  1. a4 [2-3]
  2. b4 [5-6]
  3. c4 [9-10]

It doesn't match 44 [10-11]

How can I match this one too?

You may use a much simpler regex:

/(?=(.[0-9]))./g

See the regex demo

This regex matches any char except newline and carriage return ( . ) that is a any char other than LF/CR followed with a digit.

This pattern does not match an empty string and does not require additional code to check if we matched an empty string (like if (m.index === re.lastIndex) re.lastIndex++; in anubhava's answer, that is redundant even in that solution, and this way you can avoid concatenating captured group values).

The actual value is stored in Capture group 1 that is inside a positive lookahead to allow getting overlapped matches. Since the captures are lost if we use str.match(re) , we have to rely on RegExp#exec inside a loop.

 var re = /(?=(.[0-9]))./g; var str = 'a a4 bb4 c44c'; var res = []; while((m=re.exec(str)) !== null) { res.push(m[1]); } console.log(res); 

You can use this regex with 2 captured groups:

/(.)(?=([0-9]))/g

and concatenate captured group #1 and #2 for your results.

RegEx Demo

 var re = /(.)(?=([0-9]))/g; var str = 'a a4 bb4 c44c'; var m; var results = []; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) re.lastIndex++; results.push(m[1] + m[2]); } console.log(results); //=> ["a4", "b4", "c4", "44"] 

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