Using powershell 5.1, why is my attempt to insert a newline at every regex match of myText.txt
not working as i expect?
To my knowledge My regex works fine, it matches every 5th comma.
Unfortunately The code fails to inject/replace/insert a newline at every regex match. For some reason instead it adds a newline to the end every time i run the following statement:
To test this,
Given a file, myText.txt
that trails with a ,
and looks exactly like this: ,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
Run the command below and observe the results
$splitEveryNthComma = ((Get-Content -path .\myText.txt -Raw) -replace "(?<=^((,[^,]*){5})+),]","`n,") | Set-Content -Path .\myText.txt
How can i change my code above to get the "expected result" below?
Expected result of myText.txt:
,1,2,3,4,5
,6,7,8,9,10
,11,12,13,14,15
,16,17,
Actual result of myText.txt:
,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
{new line is added to the end. This is the bug im asking about.}
Your regex can be simplified
",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17," -replace "((,[^,]*){5})", "`$1`n"
gives
,1,2,3,4,5
,6,7,8,9,10
,11,12,13,14,15
,16,17,
The regex (,[^,]*){5}
captures the first / next 5 commas (including anything after them) and appends a newline after it. The parentheses in the expression groups it for the {5}
(the outer parentheses in the code block above is what does the capture)