Regular expression for a character that appears at most once
[^.]*\.?[^.]*$
And don't forget match
, don'tsearch
>>> dot = re.compile("[^.]*\.[^.]*$")
>>> dot.match("fooooooooooooo.bar")
<_sre.SRE_Match object at 0xb7651838>
>>> dot.match("fooooooooooooo.bar.sad") is None
True
>>>
Edit
If you're only considering integers and decimal places, it's even easier:
def valid(s):
return re.match('[0-9]+(\.[0-9]*)?$', s) is not None
assert valid("42")
assert valid("13.37")
assert valid("1.")
assert not valid("1.2.3.4")
assert not valid("abcd")
source to share
No regex needed, see str.count()
:
str.count(sub[, start[, end]])
Returns the number of non-overlapping occurrences of a substring in the range [start, end]. The optional arguments start and end are interpreted as in slice notation.
>>> "A.B.C.D".count(".")
3
>>> "A/B.C/D".count(".")
1
>>> "A/B.C/D".count(".") == 1
True
>>>
source to share
As long as the period is a special char, it must be escaped. Therefore "\. +" Should work.
EDIT:
Use '?' instead of "+" to match one or zero repetitions. Look at: re - Expression Regular Operations
source to share
If the period should only exist once in the entire line, use the operator ?
:
^[^.]*\.?[^.]*$
Abort this:
-
^
matches the beginning of the line -
[^.]
matches zero or more characters that are not periods -
\.?
matches a period character (must be escaped with\
as a reserved char) exactly 0 or 1 times -
[^.]*
is the same pattern used in 2 above -
$
matches end of line
As an aside, I personally wouldn't use a regex for this (if I didn't check other aspects of the string for validity too). I would just use the count function.
source to share