How to replace all characters except the last digits

Viewed 188

I'm trying to replace the -r in this Semantic version 2020.7.28-r5 with a single period, but I'm getting this instead 2020.7.28..

Here's what I've come up with so far:

"2020.7.28-r5" -replace "(-[A-Za-z-][0-9A-Za-z-]*)", "."

A specification:

  • r will always be one or more characters (in this case simply r)
  • r can be any SemVer-legal character ([0-9A-Za-z-])
  • r will always end in a character, never a digit
  • r will always be preceded by a hyphen -
  • The final number (the build number for the day) will always be one or more digits

Based on this answer I tried this expression:

"(-[A-Za-z-][0-9A-Za-z-]*)(?=\d{4})"

But it didn't replace anything.

How can I start with 2020.7.28-The11thFantasticallyCleverUpdateForTheDay11 and end up with 2020.7.28.11?

1 Answers

You may use

-replace '-[A-Z][0-9A-Z]*?(\d+)$', '.$1'

See the regex demo. Mind that PS regex is case insensitive by default, [A-Z] is enough to match all ASCII letters.

Details

  • - - a hyphen
  • [A-Z] - any ASCII letter
  • [0-9A-Z]*? - zero or more digits or letters
  • (\d+) - Group 1 ($1 refers to this value): one or more digits
  • $ - end of string.
Related