gtx911
gtx911

Reputation: 1289

Regex and powershell - Get string before slash

I have a list of directories with files like this:

testing_module/forms/node.js
terraform_packer/globals.js
protection_list/forms/security.js

I want to get with powershell only the folder before the slash:

testing_module
terraform_packer
protection_list

I use -replace with this regex expression to test it:

'testing_module/forms/node.js' -replace '/([^/]+/[^/]+)$'

But it returns the full line.

What should I use?

Upvotes: 0

Views: 3716

Answers (3)

dan-gph
dan-gph

Reputation: 16909

I think it's nicer to positively search for what you are looking for rather than to remove what you are not looking for. Here we search from the beginning of the string for the biggest substring that doesn't contain a slash.

PS> "testing_module/forms/node.js" -match "^[^/]*"
True
PS> $matches[0]
testing_module

Upvotes: 0

Palle Due
Palle Due

Reputation: 6292

I see that as matching rather than replacing. Match any character that's not a forward slash until you meet a forward slash:

'testing_module/forms/node.js' -match '[^/]+'
$matches[0]
'terraform_packer/globals.js' -match '[^/]+'  
$matches[0]
'protection_list/forms/security.js' -match '[^/]+'
$matches[0]

It works with folders of any depth.

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174700

You could replace the first / and everything after with:

'testing_module/forms/node.js' -replace '\/.*$'

or use -split and grab only the first resulting part:

@('testing_module/forms/node.js' -split '/')[0]
# or 
'testing_module/forms/node.js' -split '/' |Select -First 1

or use the String.Remove() and String.IndexOf() methods:

$str = 'testing_module/forms/node.js'
$str.Remove($str.IndexOf('/'))

Upvotes: 2

Related Questions