matching very long and complex version numbers with regular expressions in python

Viewed 64

I have lots of lines like this.

some text some more text v3.1.0-beta.4 more & more text
some text some v2 build.3 some more text more & more text
some text some v21.1.23456.551436a4 alpha.4 some more text v16.1.2 more & more text

version numbers are:

v3.1.0-beta.4
v2 build 3
v21.1.23456.551436a4 alpha.4 and v16.1.2

The problem is I can have have words beta or build or neither in my version numbers. variable length of version numbers.

Here's what I have now and this can only match numbers.

\d+(?:\.\d+)+

How do I search for the existence of one or more version numbers in a give line like shown in above lines like above?

1 Answers

You may try this regex:

\bv[\d+]+[\w.]*(?:[-\s]+(?:alpha|beta|build)[\w.]*)?

RegEx Demo

Pattern Details:

  • \bv: Match v after a word boundary
  • [\d+]+: Match 1+ digit or dot characters
  • [\w.]*: Match 0 or more word or dot characters
  • (?:[-\s]+(?:alpha|beta|build)[\w.]*)?: starting with whitespace or hyphen, optionally match alpha|beta|build part followed by 0 or more word or dot characters
Related