-3

In python 3.6 I want to match a version number, i.e. a string that contains numbers and dots.

Here is what I have tried:

re.search(r"([\d\.+]+)", str)

but this also matches str="2020" which obviously does not contain a dot. Although I require at least one dot to match! Is that a bug or what am I misunderstanding from the documentation about the + sign?

I also tried

re.search(r"(\d+\.+)", "2020.4.3")

which does match, but only returns the string "2020.".

Here are some test cases:

abba -> No match
2020 -> No match
1.1.1.1 -> 1.1.1.1
2020.4.3 -> 2020.4.3
Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

1

You can use this regex in python to ensure at least one dot:

r'\b\d+(?:\.\d+)+'

RegEx Demo

RegEx Details:

  • \b: Word boundary
  • \d+: Match 1+ digits
  • (?:\.\d+)+: Match a group 1+ times containing dot followed by 1+ digits
anubhava
  • 761,203
  • 64
  • 569
  • 643