简体   繁体   中英

How to replace nth character occurence with another character

Given this string:

2017.12.21.5

...how would one convert it to this:

2017.12.21-5

The match will always be on the 3rd occurrence of . .

I'm running this in a PowerShell script.

I've tried too many permutations to list here; so far I haven't even come close.

--EDIT--

In addition, the second and third octets (the month and day) will vary between one and two digits. The fourth (the release for that day) may also contain three digits.

您可以使用此正则表达式匹配的第3次匹配。

(?<=\.\d+\.\d+)\.

You can use split and join

$var='2017.12.21.5'
$split=$var -split '\.'
($split[0..2] -join '.') + '-' + $split[3] 

There is not a way to target and replace the nth occurrence of a character, so we just have to target the whole string and copy over the unchanged parts

"2017.12.21.5" -replace '(\d{4}\.\d{2}\.\d{2})\.(\d*)', '$1-$2'
2017.12.21-5

Edit: I simplified the last Function to this.

$InputStr = "2017.12.21.5"
$matchVal = '.'
$replaceVal='-'
$num = 3

#searched is:
$OutputStr=$InputStr

$positions = (0..($InputStr.ToCharArray().Count-2)|ForEach-Object{$InputStr.IndexOf($matchVal,$_)}|Select-Object -Unique)
if($num -lt $positions.Count+1){
    $OutputStr = $InputStr.Remove($positions[$num-1],1).Insert($positions[$num-1], $replaceVal)
}

so it gets all positions of the $matchVal in $positions and then checks if $num <= Count of positions. If so, the $InputStr 's char at $position[$num-1] will be replaced with the $replaceVal .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM