0

Regex is still a new concept to me, but I had a piece of code that troubled me because I spent a while trying to figure out how to format decimals correctly with -replace in order to shave some extra decimal points. This is the original list I was working with:

1.20                                    
1.150000                                
1.10                                    
1.10                                    
1.000000                                
1.00                                    
1.00                                    
0.90                                    
0.90  

Playing around with http://regexr.com/, I managed this regex: (\.\d{2})(\d{4}) with a replace value of $1, which resulted in:

1.20                                    
1.15                                
1.10                                    
1.10                                    
1.00                                
1.00                                    
1.00                                    
0.90                                    
0.90  

This is exactly what I wanted, but I don't understand why the regex worked or whether it is the cleanest solution. According to regexr, both capture groups highlighted the two numbers with the extra decimal places from '.' onwards. Capture group #1 would've highlighted the decimal and the first two decimal places of every number on the list while #2 would've highlighted the first 4 decimals minus the '.' in the two outlier numbers. I'm not sure how specifying capture group 1 resulted in the clean list, however.

Could someone explain how this regex with -replace functioned and whether or not this was the cleanest solution? Thanks!

  • A better regex can be: `[+-]?(\d+\.\d+|\.\d+|\d+)` ;). – shA.t Aug 30 '17 at 12:53
  • 4
    There are tons of resources explaining the regex. The regex is so basic that you may check it at http://regex101.com (as it is compatible with any regex flavor supported by that site). Whether it is the best or not we can't tell you because you did not provide *exact* requirements. – Wiktor Stribiżew Aug 30 '17 at 12:53
  • 1
    @shA.t Yeah, we may play the guessing game. All we can do now. – Wiktor Stribiżew Aug 30 '17 at 12:53
  • @WiktorStribiżew Sorry, only requirement here is having all numbers with 2 decimal places no rounding. I'll look at the site you provided, thank you. –  Aug 30 '17 at 13:56
  • Ok, still, it is really extremely basic - just use `+` instead of `{4}` to match 1 or more occurrences. See http://regexone.com, it will give you a boost in regex. – Wiktor Stribiżew Aug 30 '17 at 13:58
  • Why not `[Math]::Truncate($n * 100) / 100`? You don't need to use Regex for that. – Thomas Glaser Aug 30 '17 at 13:59
  • @WiktorStribiżew Thanks. I'll check that out. –  Aug 30 '17 at 14:03
  • @Raziel I could. In the actual code I'm piping into this, so I don't know if that can work too but if it does that's great. –  Aug 30 '17 at 14:04

0 Answers0