Can these two regular expressions (match and replace) be combined into a single operation?

Viewed 41

I'm extracting a four-part version number from a filename and converting it to a SemVer-compliant version.

  1. Filename: MyApp v2020.8.3.1.exe
  2. SemVer: 2020.8.3-r1

I've been successful at doing this using two steps:

sVersion = Regex.Match("MyApp v2020.8.3.1.exe", "[A-Za-z ]|\.[A-Za-z]").Value
oSemver = New Regex("\.(?=[^\.]+$)")
sSemVer = oSemver.Replace(sVersion, "-r")

This produces the desired SemVer-compliant version.

However, for the sake of brevity, I'd like to combine these two steps into a single operation.

I tried several variations on a couple of Q&As I found:

...but I didn't have much luck.

For example:

([A-Za-z ]|\.[A-Za-z])|(\.(?=[^\.]+$)) replaced with $2 produces only the four-part version number 2020.8.3.1.

Is this possible, given the constraints I'm working with?

--EDIT--

I only need a SemVer-compliant version number, not a new filename. In other words, I need to strip off all the extraneous characters (in this case MyApp v and .exe) and replace the final . in the four-part version number with -r.

1 Answers

If i understand what you want (and i am not sure i do)

Update

var input = "MyApp v2020.8.3.1.exe";
var m = Regex.Match(input, @"(\d+)\.(\d+)\.(\d+)\.(\d+)");
var result = $"{m.Groups[1]}.{m.Groups[2]}.{m.Groups[3]}-r{m.Groups[4]}";
Console.WriteLine(result);

Output

2020.8.3-r1

Full Demo Here

or you could just use (\d+\.\d+\.\d+)\.(\d+) which would result in 2 groups


Original

var input = "MyApp v2020.8.3.1.exe";
var result = Regex.Replace(input, @"(\d+)\.(\d+)\.(\d+)\.(\d+)", "$1.$2.$3-r$4");
Console.WriteLine(result);

Output

MyApp v2020.8.3-r1.exe

Full Demo Here

Related