Eric B Eric B - 14 days ago 5
C# Question

regex to replace last two digits of an assemblyversion

I'm working with teamcity and a C# project, and I want to use the file content patcher to replace the last two digits in an assemblyversion (eg: the two stars in

[assembly: AssemblyVersion("1.0.*.*")]
). I've found the docs on the file content patcher and it suggests using

(^\s*\[\s*assembly\s*:\s*((System\s*\.)?\s*Reflection\s*\.)?\s*AssemblyVersion(Attribute)?\s*\(\s*@?\")(([0-9\*]+\.)+)[0-9\*]+(\"\s*\)\s*\])
if you just want to change the LAST digit, which got me partway there.

I figured if I did
(^\s*\[\s*assembly\s*:\s*((System\s*\.)?\s*Reflection\s*\.)?\s*AssemblyVersion(Attribute)?\s*\(\s*@?\")(([0-9\*]+(\.))+)[0-9\*]+(\"\s*\)\s*\])
it would capture the last period as it's own group, letting me replace the two stars without a problem. However it looks like the first star is still captured in the group with the 1.0 (so the group becomes 1.0.*.).

What I want is to restrict the first group to capturing the {major}.{minor}. and then have the last period be it's own group so I could do something like:
$1$5\%build.number%$7%build.vcs.number%$8
which would give me
AssemblyVersion("1.0.{build#}.{vcs#}")]


Generally I can stumble through regex without many problems but I've been working on this for the last few hours and I can't seem to get it correct. Any information on reaching this conclusion would he appreciated.

Answer

If you want to keep to the solution you found to replace while also validating, you may use

(^\s*\[\s*assembly\s*:\s*((System\s*\.)?\s*Reflection\s*\.)?‌​\s*AssemblyVersion(A‌​ttribute)?\s*\(\s*@?‌​\")([0-9\*]+\.[0-9\*‌​]+)\.([0-9\*]+\.[0-9‌​\*]+)(\"\s*\)\s*\])

and replace with $1$5.%build.number%.%build.vcs.number%$7.

See the regex demo

I just unrolled the ([0-9\*]+(\.))+ into ([0-9\*]+\.[0-9\*‌​]+)\.([0-9\*]+\.[0-9‌​\*]+), 2 groups (([0-9\*]+\.[0-9\*‌​]+)) separated with a literal dot (\.). I also had to remove the [0-9\*]+ that followed the ([0-9\*]+(\.))+ pattern.