Stephen Cousins
Stephen Cousins

Reputation: 39

How do I add characters before and after other characters in a text string in Powershell

My code captures a string of numbers from another file using regex (.*) There should always be a minimum of four numbers

The output may be

1456 or 234567

But let’s say it’s

3667876

I want to add ‘km ’ before the last three digits a ‘m’ after the last three digits. So resulting in

3667km 876m

The line of code in the Powershell script is

Get-Content -Tail 0 -Wait -Encoding "UTF8" $log | 
  Select-String "Run Distance: (.*)" |
   % {"Total Distance `- " + $_.matches.groups[1].value} |
    Write-SlowOutput -outputFile $output -waitFor $delay

So in this case the output would read

Total Distance - 3667km 876m

Can anyone help with the regex formula to use in place of the (.*) in this Powershell script.

Thank you

Upvotes: 0

Views: 2044

Answers (3)

Lee_Dailey
Lee_Dailey

Reputation: 7479

here's yet another way to do the job. [grin] you can use a regex pattern with the -replace operator to replace the digits in the string & build a new string with the match groups. like this ...

'1234' -replace '(.+)(.{3})$', '$1km $2m'

output = 1km 234m

the glitch with this is that the number must have at least 4 digits to work correctly. if you may have fewer digits to work with, then a solution similar those by Thomas or FoxDeploy are needed.

Upvotes: 3

FoxDeploy
FoxDeploy

Reputation: 13537

If you like some more readable code, you can also do this easily by casting your int number into a string using ToString() and then use Substring() to slice it apart. The result is very easy to read.

ForEach($n in $nums){
    $splitIndex = $n.ToString().Length - 3    
    $KMs =  $n.ToString().Substring(0,$splitIndex)
    $Meters = $n.ToString().SubString($splitIndex, 3)
    "Total distance $KMs Kilos - $Meters meters"
}

Resulting in

Total distance 3667 Kilos - 876 meters
Total distance 33667 Kilos - 876 meters
Total distance 45454 Kilos - 131 meters

Upvotes: 1

stackprotector
stackprotector

Reputation: 13432

I don't have the Write-SlowOutput cmdlet, but the output of the ForEach-Object cmdlet looks fine:

Get-Content -Tail 0 -Wait -Encoding "UTF8" $log | 
    Select-String "Run Distance: (\d+)(\d{3})$" |
    % {"Total Distance `- $($_.matches.groups[1].value)km $($_.matches.groups[2].value)m"} |
    Write-SlowOutput -outputFile $output -waitFor $delay

I implemented two matching groups in the regex to be able to process them individually.

Upvotes: 2

Related Questions