How to get sub string from a string

This topic contains 2 replies, has 3 voices, and was last updated by  Stephen Owen 3 years, 5 months ago.

  • Author
  • #21645

    Shafaqat Ali

    I am trying to get sub string from a string with powershell

    $completeString = "C:\Development\Work\ABC-SharePoint\ABC\css\ABC\XYZ"

    $startingString = "ABC"

    I want "ABC\css\ABC\XYZ"

    note: ABC is multiple times in string

  • #21646

    Dave Wyatt

    That's kind of tricky to answer with the limited information available. You have the string "ABC" here in "ABC-Sharepoint", but you were interested in that part in the output. Are you looking for the first instance of "\ABC\" and then everything else in the string? Or everything after "C:\Development\Work\ABC-SharePoint\"? Something else entirely?

    Here's one example that gives you everything after (and including) the first instance of a folder named exactly ABC (not case sensitive).

    $completeString = "C:\Development\Work\ABC-SharePoint\ABC\css\ABC\XYZ"
    $startingString = "ABC"
    $pattern = "^.*?\\(?=$([regex]::Escape($startingString))\\)"
    $completeString -replace $pattern

    This particular example uses a regular expression, which is a very powerful technique that is also a pain in the butt to read. Another alternative would be to split the string on the backslashes (or use the Split-Path cmdlet) and loop over the resulting array yourself to find the first instance of "ABC", then join the rest of the array together. That code might look like this:

    $completeString = "C:\Development\Work\ABC-SharePoint\ABC\css\ABC\XYZ"
    $startingString = "ABC"
    $array = $completeString -split '\\'
    for ($i = 0; $i -lt $array.Count; $i++)
        if ($array[$i] -eq $startingString) { break }
    $array[$i..($array.Count - 1)] -join '\'
  • #21680

    Stephen Owen

    I don't know what happened to your code there when you pasted, Dave, but I think the last line should be

    $array[$i..($array.Count)] -join '\'

You must be logged in to reply to this topic.