How does this regex work in js?

Asked

Viewed 178 times

4

I found on the internet this regex in javascript that formats monetary values in R$:

Number( 1450999 )
.toFixed( 2 )
.replace( '.', ',' )
.replace( /(\d)(?=(\d{3})+,)/g, "$1," )
// 1450999 -> 1.450.999,00

I’ve been analyzing it for a long time and I still don’t understand how this regex works. For example, in the case regex does a global search, but if I remove this parameter, the return is a match for digit 1:

Number( 1450999 )
.toFixed( 2 )
.replace( '.', ',' )
.replace( /(\d)(?=(\d{3})+,)/, "$1." )
// 1450999 -> 1.450999,00

The question is as follows, how can this regex take digit 1 as a match if it is not followed by 3 digits and a comma, just like the regex. You wouldn’t have to take the digit 0?

  • Because the character "?" indicates an optional match that may or may not be there

  • You took the g in both examples... it was right mistake?

  • 1

    In the regex documentation of Mozilla, it says that this is a "Lookahead", and that in this case x(?=y), x only matches if it is followed by y, so it would not be optional.

  • yes Sergio, I accidentally removed :b

  • The link to the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions. That’s why I’m not sure how this regex works

1 answer

3


When you have .replace(/(\d)(?=(\d{3})+,)/g, "$1.") what’s going on is this:

The line Number(1450999).toFixed(2).replace('.', ',') turns your number into a string like this: "1450999,00". And it is about this string that regex acts:

  • (\d) creates a capture group with only numbers
  • (?=(\d{3})) indicates that the first closed capture group should look for (\d{3})
  • (\d{3})+ creates a capture group of numbers, grouped 3 to 3, once or more (+)
  • , indicates that after captures all come a comma in the string
  • g indicates that you should continue searching after you have found a first match

then replace each group of 3 numbers by these 3 numbers but adding a point.

There is an excellent site to analyze regular expressions. In your case it would be like this: https://regex101.com/r/Z2UIc/1

  • 1

    Ahhhh, I get it now. The problem is that I was looking at the '+' as regex, I was seeing it as an additional saying that it would be 3 digits + a comma, but in this case it looks for the preceding 1 or more times (in case, d{3}), just as Oce explained. Thanks Sergio, I understand now, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.