-2

Is there any easy way to do this?

input: 123215-85_01_test

expected output: 01_test

Another example

input: 12154_02_test

expected output: 02_test

There will be always string "test", but different numbering before

for example this code..

$path = "c:\tmp\*.sql"
get-childitem $path | forEach-object {


   $name = $_.Name 
   $result = $name -replace "",""  # I don't know how write this regex..
   $extension = $_.Extension
   $newName = $prefix+"_"+ $result -f, $extension
   Rename-Item -Path $_.FullName -NewName $newName

}
charles
  • 217
  • 1
  • 6
  • 14
  • 1
    Easy way to do what? Where is your regex? Where does that input and output come from? Where is the code that generates this? – arco444 Nov 11 '15 at 14:17
  • 1
    now there is example – charles Nov 11 '15 at 14:27
  • So you always need the part at the end? It is _always_ what follows the second last underscore? You don't even _really_ need regex for this then if that is the case. – Matt Nov 11 '15 at 14:31
  • 1
    Possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – briantist Nov 11 '15 at 14:39
  • @briantist I really enjoy that post as it covers a lot of ground. Are you using that for "gimmie the regex" questions as a place for OP's to start? – Matt Nov 11 '15 at 14:42
  • @Matt yeah exactly, I was clued into it from [this meta post](http://meta.stackoverflow.com/questions/285733/should-give-me-a-regex-that-does-x-questions-be-closed) and it seemed like a good idea to me for questions that don't show any research. It has a lot of good information to get started. – briantist Nov 11 '15 at 15:09

1 Answers1

1

There are two ways you go go at this. Simple split and join or you can use one of many regexes....

Split on underscore and rejoin last 2 elements

$split = "123215-85_01_test" -split "_"
$split[-2..-1] -join "_" # $split[-2,-1] would also work.

Regex to locate the data between the last underscores

"123215-85_01_test" -replace "^.*_(\d+)_(.*)$", '$1_$2'

Note this fails if there is more than 2 underscores.

Matt
  • 40,384
  • 7
  • 62
  • 97