Daniel G. Reina Daniel G. Reina - 3 months ago 11
Javascript Question

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?

Answer

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);

Comments