Ryvik
Ryvik

Reputation: 473

Getting first two strings between slashes

I have a string, alpha/beta/charlie/delta

I'm trying to extract out the string alpha/beta including the forward slash.

I'm able to accomplish this with split and joining the first and second result, but I feel like a regex might be better suited.

Depending on how many slashes there are as well will determine how many strings I need to grab, e.g. if there's 4 slashes get the first two strings, if there's 5, then grab first three. Again, my problem is extracting the slash with the string.

Upvotes: 0

Views: 828

Answers (3)

LosFla
LosFla

Reputation: 119

You can try the .split() .net method where you define in parentheses where to split (on which character).

Then use the join operator “-join” to join your elements from the array

For your matter of concern use it like this:

$string = 'alpha/beta/charlie/delta/gamma'
$string = $string.split('/')
$string = "$($string[0])" + "/" + "$($string[1])"
$string

And so on...

Upvotes: 0

Olaf
Olaf

Reputation: 5242

As Mathias already noticed - Split+Join is a perfectly valid solution:

$StringArray = @(
    'alpha/beta/charlie/delta',
    'alpha/beta/charlie/delta/omega'
    'alpha/beta/charlie/gamma/delta/omega'
)
foreach ($String in $StringArray) {
    $StringSplit = $String -split '/'
    ($StringSplit | Select-Object -First ($StringSplit.Count - 2) ) -join '/'
}

Upvotes: 3

Vish
Vish

Reputation: 466

A little long, but I did it without regex:

$string = 'alpha/beta/charlie/delta/gamma'

# Count number of '/'
$count = 0

for( $i = 0; $i -lt $string.Length; $i++ ) {
    if( $string[ $i ] -eq '/' ) {
        $count = $count + 1
    }
}

# Depending on the number of '/' you can create a mathematical equation, or simply do an if-else ladder.
# In this case, if count of '/' = 3, get first 2 strings, if count = 4, get first 3 strings.

function parse-strings {
    Param (
        $number_of_slashes,
        $string
    )

    $all_slash  = $number_of_slashes
    $to_get     = $number_of_slashes - 1
    $counter    = 0

    for( $j = 0; $j -lt $string.Length; $j++ ) {
        if( $string[ $j ] -eq '/' ) {
            $counter = $counter + 1
        }
        if( $counter -eq $to_get ) {
            ( $string[ 0 .. ( $j - 1 ) ] -join "" )
            break
        }
    }
}

parse-strings -number_of_slashes $count -string $string

Upvotes: 0

Related Questions