Reputation: 3291
^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]+\.[0-9]*[1-9][0-9]*)$
I don't know regular expression well. Above regular expression does not allow input .2 .but it allows all other decimals like 0.2 , 0.02 etc . I need to make this expression allow the number like .2 ,.06 , etc.....
Upvotes: 3
Views: 12597
Reputation: 1
I have been working on this from quite a while I got a some good expression that works well
[+-]?(?:\d+|\D{0}\.\d+)(?:\.\d+)?
It identifies numbers/decimals with with/without leading 0's. Here is the demo on regx101
Adding demo here in case link do not works
import re
x = "string .001 or -.001 or 1.00 or -1.00 or-213 or 123.132s1 or 012"
print(re.findall(r"[+-]?(?:\d+|\D{0}\.\d+)(?:\.\d+)?", x))
O/P
['.001', '-.001', '1.00', '-1.00', '-213', '123.132', '1', '012']
Upvotes: 0
Reputation: 10514
Replace it with:
^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]*\.[0-9]*[1-9][0-9]*)$
or even shorter:
^(\d*[1-9]\d*(\.\d+)?|[0]*\.\d*[1-9]\d*)$
Upvotes: 0
Reputation: 655209
I would use this:
^(?:(?:0|[1-9][0-9]*)(?:\.[0-9]*)?|\.[0-9]+)$
This allows number expressions starting with either
Allowed:
123
123.
123.45
.12345
But not:
.
01234
Upvotes: 2
Reputation: 106332
I like this regexp for floating point numbers, its pretty smart in that it wont match 0.0
as a number. It requires at least one non-zero number on either side of the period. Figured I'd break it into its parts to provide a deeper understanding of it.
^ #Match at start of string
( #start capture group
[0-9]* # 0-9, zero or more times
[1-9] # 1-9
[0-9]* # 0-9, zero or more times
( #start capture group
\. # literal .
[0-9]+ # 0-9, one or more times
)? #end group - make it optional
| #OR - If the first option didn't match, try alternate
[0]+ # 0, one or more times ( change this to 0* for zero or more times )
\. # literal .
[0-9]* # 0-9, zero or more times
[1-9] # 1-9
[0-9]* # 0-9, zero or more times
) #end capture group
$ #match end of string
The regexp has two smaller patterns inside of it, the first matches cases where the number is >= 1 (having at least one non-zero character left of the .) optionally allowing for a period with one or more trailing numbers. The second matches <1.0 and ensures that there is at least one non-zero digit on the right side of the dot.
Johannes' answer already gives you the [0]*
solution to the problem.
Couple of regexp shortcuts, you could replace any instance of [0-9]
with \d
in most regexp flavors. Also [0]
only matches 0
so you might as well just use 0*
instead of [0]*
. The final regexp:
/^(\d*[1-9]\d*(\.\d+)?|0*\.\d*[1-9]\d*)$/
Upvotes: 8
Reputation: 354426
Just change the +
after [0]
into an ansterisk `*":
^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]*\.[0-9]*[1-9][0-9]*)$
So instead of allowing one or more zeroes preceding the dot, just allow 0 or more.
Upvotes: 11