Creating a regex to parse a build version
I'm tyring to grab a build verson from a file that contains the following line:
<Assembly: AssemblyVersion("004.005.0862")>
and I would like it to return
4.5.862
I'm using sed in dos and got the following to spit out 开发者_开发问答004.005.0862
echo "<Assembly: AssemblyVersion("004.005.0862")>" | sed "s/[^0-9,.]//g"
How do I get rid of the leading zeros for each part of the build number?
The regex to do this in a single step looks like this:
^.*"0*([0-9]+\.)0*([0-9]+\.)0*([0-9]+).*
with sed-specific escaping and as a full expression, it becomes a little longer:
s/^.*"0*\([0-9]\+\.\)0*\([0-9]\+\.\)0*\([0-9]\+\).*/\1\2\3/g
The regex breaks down as
^ # start-of-string .*" # anything, up to a double quote 0*([0-9]+\.) # any number of zeros, then group 1: at least 1 digit and a dot 0*([0-9]+\.) # any number of zeros, then group 2: at least 1 digit and a dot 0*([0-9]+) # any number of zeros, then group 3: at least 1 digit .* # anything up to the end of the string
Maybe ... | sed "s/[^0-9]*0*([1-9][0-9,.]*)/\1/g"
. I'm using a subpattern to filter out the part you need, ignoring leading zeros and non-numeric characters.
There are probably many more clever ways, but one that works (and is reasonably easy to understand) is to pipe it through additional calls:
echo "version(004.005.0862)" | sed "s/[^0-9,.]//g" | sed "s/^0*//g" | sed "s/\.0*/./g"
精彩评论