1

I have to add commas to this string: 1321654987.00 The result should be: 1,321,654,987.00

I'm trying to use substitutions:

'123123897.00' -replace '^(?<start>(\d{1,3}))(?<mid>(\d{3}))*(?<end>(\.\d{2}))?$','${start},${mid}${end}'

But the result is following: 1,987.00

How can I replace each matched group, not the last one?

Thanks in advance!

2
  • 3
    I think you're taking the wrong approach to this. Does .NET numeric formatting work better for you? Commented Aug 4, 2017 at 10:24
  • I think $s -replace '(?<!\..*)\B(?=(?:\d{3})+(?:\.\d+)?$)', ',' will work, but Mike is right, a regex is not what you really need here. Commented Aug 4, 2017 at 10:32

1 Answer 1

2

The regex could be something like this

'123123897.00' -replace '(?m)(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))', ','

explanation

# (?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))
# 
# Options: Case sensitive; Exact spacing; Dot doesn't match line breaks; ^$ match at line breaks; Parentheses capture
# 
# Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=[0-9])»
#    Match a single character in the range between “0” and “9” «[0-9]»
# Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=(?:[0-9]{3})+(?![0-9]))»
#    Match the regular expression below «(?:[0-9]{3})+»
#       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
#       Match a single character in the range between “0” and “9” «[0-9]{3}»
#          Exactly 3 times «{3}»
#    Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?![0-9])»
#       Match a single character in the range between “0” and “9” «[0-9]»
# Your regular expression may find zero-length matches
#    PowerShell allows a zero-length match at the position where the previous match ends.
#    PowerShell advances one character through the string before attempting the next match if the previous match was zero-length.

That being said, Mike is right that you should be using formatting functions. Following should suffice

"{0:N2}" -f 123123897.00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.