Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell I want to cut off a string after a specific character sequence

I am trying to parse a string variable where everything after -354 gets cut off.

I have variables that look like this: NameOfFile-354-XX.pdf

Where NameOfFile can be any length and -XX can be anything or not even there at all.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want the print of this variable to be: NameOfFile-354

How do I cut the variable so it cuts after -354?

What I have tried so far:

$FileArray = @("Name1-354-03.pdf", "Name23-354-H11.pdf", "Name354-354-02.pdf", "Name3545-354.pdf")
ForEach ($n in $FileArray){
     Write-Host $n.Substring(0, $n.lastIndexOf('-354'))
}

I want the output to be this:

Name1-354
Name23-354
Name354-354
Name3545-354

Thank you for your help.

>Solution :

I am not a regex pro but would something like this work for you?

$string = "NameOfFile-354-XX.pdf"
$regex = "(.*)(-[a-zA-Z0-9]+(.)(.*))"
$match = $string -replace $regex,'$1'

Output would be like this:

PS C:\temp> $string = "NameOfFile-354-XX.pdf"
$regex = "(.*)(-[a-zA-Z0-9]+(.)(.*))"
$match = $string -replace $regex,'$1'

Write-Host $match
NameOfFile-354

PS C:\temp> 

Regex details: https://regex101.com/r/Fw8F3i/1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading