0

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.

0

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

5 Comments

Just play with removing the last .* on the regex in the demo site. You should see the difference.
Awesome, not only does this work perfectly but you've managed to help me understand why whatever I was trying didn't work.
Explained because of 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. It's good to ask for explanation.
Thanks. And also thanks for the link to that site, I didn't happen to use that one when I was searching for online tools but it seems a lot better than the ones I used because it explains the regex and why it works.
Yes, i think it's the best online regex site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.