Don Cummins
Don Cummins

Reputation: 77

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.

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.

Upvotes: 3

Views: 2374

Answers (3)

mklement0
mklement0

Reputation: 439307

A regex solution - such as in Santiago Squarzon's helpful answer - is definitely an option, but the only thing missing from your original attempt is to add the length of the substring you're searching for - i.e. '-354'.Length == 4 - to the 2nd .Substring() argument, so as to include that substring in the string returned:

"Name1-354-03.pdf", "Name23-354-H11.pdf", "Name354-354-02.pdf", "Name3545-354.pdf" | 
  ForEach-Object {
    $_.Substring(0, $_.LastIndexOf('-354') + 4) # Note the + 4
  }

Upvotes: 1

Santiago Squarzon
Santiago Squarzon

Reputation: 60563

Assuming -354 is a constant value:

$FileArray = [System.IO.FileInfo[]]@(
    "Name1-354-03.pdf", "Name23-354-H11.pdf", "Name354-354-02.pdf", "Name3545-354.pdf"
)
$FileArray.ForEach({ $_.Name -replace '(?<=-354).*(\.pdf)', '$1' })

# Outputs:
Name1-354.pdf
Name23-354.pdf
Name354-354.pdf
Name3545-354.pdf

For regex explanation: https://regex101.com/r/4Butm2/1

Upvotes: 2

DSSO21
DSSO21

Reputation: 129

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

Upvotes: 1

Related Questions