0

I have tried writing a code for identifying decimal number in python using regular expression as indicated in the below code.

It is working fine for many case but still failing to identify below inputs

import re
string = input()
r = re.compile(r"([+\-.]?\d*\.\d+)\b")
if(r.match(string)):
    print(True)
else: 
    print(False)

234.2344 ->for this input giving expected results

+.3456468 ->for this input giving expected results

5.34.0 -> for this input it should print False

4+345.0 -> for this input it should print False

San
  • 363
  • 3
  • 11

3 Answers3

4

These expressions might likely validate integer and decimal numbers:

^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$

or

^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$

if for instance 1. would be valid.

DEMO 1

DEMO 2

Test

import re

regex = r"^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$"

test_str = ("0.00000\n"
    "0.00\n"
    "-100\n"
    "+100\n"
    "-100.1\n"
    "+100.1\n"
    ".000\n"
    ".1\n"
    "3.\n"
    "4.")

print(re.findall(regex, test_str, re.MULTILINE))

Output

['0.00000', '0.00', '-100', '+100', '-100.1', '+100.1', '.000', '.1']

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

The expression is explained on the top right panel of this demo if you wish to explore/simplify/modify it.

Emma
  • 27,428
  • 11
  • 44
  • 69
1

You can use

^[+-]?(?:\.\d+|\d+(?:\.\d+)?)$

enter image description here

Python demo|Regex Demo

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Use beginning ^ and end anchors $ if you don't want it to match the first decimal-like part:

import re
decimal_re = re.compile(r'^\D?[+-]?\d*\.?\d+$')

cases = [
    '234.2344',
    '+.3456468',
    '5.34.0',
    '4+345.0',
    '1.5555',
    '.123123',
    '456.',
    '4.4.5.5'
]
for c in cases:
    print(decimal_re.match(c))

output:

<re.Match object; span=(0, 8), match='234.2344'>
<re.Match object; span=(0, 9), match='+.3456468'>
None
None
<re.Match object; span=(0, 6), match='1.5555'>
<re.Match object; span=(0, 7), match='.123123'>
None
None
abdusco
  • 9,700
  • 2
  • 27
  • 44