-2

Is there a regular expression which would match floating point numbers but not if this is a part of a construct like 15.01.2016?

re.match(rex, s) should be successful if s would be

1.0A
1.B
.1

and not successful for s like

1.0.0
1.0.1
20.20.20.30
12345.657.345

Edit: The crucial part is the combination of the constrains: "[0-9]*\.[0-9]*" and not part of "[0-9]+\.[0-9]+(\.[0-9]+)+"

ead
  • 32,758
  • 6
  • 90
  • 153
  • I can match doubles and something like xxx.xxx.xxx the combination of both constrains is the problem – ead Jan 15 '16 at 21:59
  • Could you show your regex expression for that? – Anton Protopopov Jan 15 '16 at 21:59
  • 1
    To answer the question you actually asked: *Yes, there is*. But I second Anton’s comment. You may wish to refer to the help files, particularly [how to ask a good question](http://stackoverflow.com/help/how-to-ask). Also, check the docs for lookahead assertions. – Tom Zych Jan 15 '16 at 22:00
  • 1
    You can use `\d` instead of `[0-9]` – RedLaser Jan 15 '16 at 22:09
  • @Anton Protopopov I updated the question with my regexes and narrowed the scope of the question to the crutial part – ead Jan 15 '16 at 22:12
  • `Sentence 1.2nd Sentence.` –  Jan 15 '16 at 22:25
  • 2
    Somebody is just duplicate crazy here.. This is not a normal float match. –  Jan 15 '16 at 22:55

2 Answers2

4

You can use this regex based on look arounds in python:

(?<![\d.])(?:\d*\.\d+|\d+\.\d*)(?![\d.])

RegEx Demo

  • (?![\d.]) is lookahead assertion to fail the match if next char is DOT or digit
  • (?<![\d.]) is lookbehind assertion to fail the match if previous char is DOT or digit
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

The following solution uses also lookahead and lookbehind as anubhava mentioned. Additionally it takes care of negative numbers, the powers of ten (also negative ones) and integers (witout a .):

(?<![\d.])-?(?:\d+\.?\d*|\d*\.\d+)([eE]-?\d+)?(?![.\d])

If you add some additional characters in the lookabehind (?<![\d.]) you can avoid matches in a random bunch of characters or at the end of a word (e.g. if you want no match for "python3" ).

Snow bunting
  • 1,120
  • 8
  • 28