George Kendros
George Kendros

Reputation: 824

powershell regex capture to pull version number

I'm struggling to understand regex's in powershell. On Friday user mike-z helped me out with a script to extract the number from a group of folders with a naming convention like this -

Core_1.1.2
Core_1.3.4 

The following regex;

-replace '.*_(\d+(\.\d+){1,3})', '$1')

works perfectly to extract only the numbers (eg "1.1.2").

Unfortunately, I later realized that a couple of the folder names had some other junk text trailing the version numbers (eg. Core_1.2.4_Prod). I tried on my own to tweak the above regex to make it also ignore the trailing text but I didn't get too far. I used various online regex generators as well as my own limited regex experience but I didn't get anywhere; I was able to generate regexes which should capture the text I need but they didn't work in powershell. Converesely, the working regex above (as in it works in powershell) fails in any regex tool I used.

Basically, given a list of folder names like this

Core_1.1.2
Core_1.2.4_Prod
Core_1.2.6
Core_1.3.1_Prod
Core_1.4.4

I need to capture just the version number. Also, it would be greatly appreciated if you could explain why the regex works as I'm extremely confused by PS regexes at this point.

Upvotes: 0

Views: 4876

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You just need to add .* at the last in your pattern,

.*_(\d+(\.\d+){1,3}).*

So your code would be,

-replace '.*_(\d+(\.\d+){1,3}).*', '$1')

DEMO

By default replace function in all the languages should replace the matched characters only. Your regex .*_(\d+(\.\d+){1,3}) matches upto the last digit in the version number. It won't match the remaining part. So whenever you replace the matched characters with $1, the trailing part _Prod should be printed along with the characters inside the first capturing group , because the trailing part is not matched. Just match also the trailing part , inorder to replace the whole line with $1(ie; version number).

Upvotes: 4

Related Questions