Using PowerShell I am trying to use Regex on the example string to capture everything starting at the third "/" and stop before the last "/". Do you know the best Regex example to do this?
Example Test String: (structure is the same but text could be random)
/example/text/istyped/HERE.TXT
/example/text/canbetyped/HERE.TXT
/example/text/sometimestyped/HERE.TXT
CODE EXAMPLE
$Example = '/example/text/typed/HERE.TXT # This $Example is imported from CSV
/example/text/istyped/HERE.TXT
/example/text/canbetyped/HERE.TXT
/example/text/sometimestyped/HERE.TXT'
$Output = $Example | where { $_.ExampleHeader -match '(My Pattern Here' }
$Output
My Output should simply be:
/typed
/istyped
/canbetyped
/sometimestyped
CodePudding user response:
If you have a recurring character in your input string you want split it on you can use the -split
operator and pick the desired element with the index of the resulting array:
$Example = @'
/example/text/typed/HERE.TXT
/example/text/istyped/HERE.TXT
/example/text/canbetyped/HERE.TXT
/example/text/sometimestyped/HERE.TXT
'@ -split "`n"
foreach($element in $Example){
($element -split '/')[3]
}
The Output would look like this:
typed
istyped
canbetyped
sometimestyped
Of course you can add a slash in front of every element if you really need. ;-)
CodePudding user response:
I suggest you to construct your regex pattern by searching with the end of the string.
Something like that should do the job :
. (\/[^\/] )\/. $
this way, you capture the last group between to slashes. It is certainly perfectible :)
You can test it here : https://regex101.com/r/Ne5IVQ/1