thesuperiorspider
thesuperiorspider

Reputation: 11

Is there a way to replace the first two occurrences of a value in a string?

I am going to be as clear with my question as I can. I might be missing something very obvious here but I just don't know how to find a solution...

I have a string and I would like to replace the first two occurrences of ":" with "/":

String:

$string = 2020:10:07 08:45:49

Desired String:

2020/10/07 08:45:49

I have tried using .Replace as seen below:

$string = $string.Replace([regex]":","/",2)

But I am given this error every time:

Cannot find an overload for "replace" and the argument count: "3".

I have seen others use .Replace in this way before so I'm not sure what is so different about my usage. Can anyone point me in the right direction?

Upvotes: 1

Views: 318

Answers (2)

filimonic
filimonic

Reputation: 4634

PowerShell is .net-based language. String does not have overload method Replace with anything like count argument in .Net, but Python's string does.

You can use this:

$string = '2020:10:07  08:45:49'
#Replace 2+ spaces you have in source with single space
$string = $string -replace '\s+', ' '

# Variant 0 - Best - ALWAYS use proper types. There is DateTime type to use for Dates and Times!    
    #Exact parse by format to DateTime object
    $dt = [DateTime]::ParseExact($string, 'yyyy:MM:dd hh:mm:ss', [System.Globalization.CultureInfo]::InvariantCulture)
    #Convert DateTime to String
    $result = $dt.ToString('yyyy\/MM\/dd hh:mm:ss')

.Net's String.Split has optional parameter count that means split no more than into # pieces. You can use it:

# Variant1
$result = [string]::Join('/',$string.Split(':', 3))

# Variant2
$result = $string.Split(':', 3) -join '/'

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

String.Replace() does not support regex patterns, nor does it accept a maximum count.

Use the -replace regex operator instead:

$string = '2020:10:07  08:45:49'
$string -replace '(?<=^[^:]*):(.*?):','/$1/'

This will replace only the first and second occurrence of : with /


Specifically for date/time representations, you may want to parse it as such, at which point you can easily re-format it:

$string = '2020:10:07  08:45:49'
$datetime = [datetime]::ParseExact($string, "yyyy:MM:dd  HH:mm:ss", $null)

# Now we can create a new string with the desired format
Get-Date $datetime -Format 'yyyy/MM/dd  HH:mm:ss'

# This might be easier than figuring out regex patterns
'{0:dd/MMM/yyyy-HH.mm.ss}' -f $datetime

Upvotes: 1

Related Questions