[ACCEPTED]-regex for character appearing at most once-regex

Accepted answer
Score: 10
[^.]*\.?[^.]*$

And be sure to match, don't search

>>> dot = re.compile("[^.]*\.[^.]*$")
>>> dot.match("fooooooooooooo.bar")
<_sre.SRE_Match object at 0xb7651838>
>>> dot.match("fooooooooooooo.bar.sad") is None
True
>>>

Edit:

If you consider 1 only integers and decimals, 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")
Score: 5

No regexp is needed, see str.count():

str.count(sub[, start[, end]])

Return the number 4 of non-overlapping occurrences of substring 3 sub in the range [start, end]. Optional 2 arguments start and end are interpreted 1 as in slice notation.

>>> "A.B.C.D".count(".")
3
>>> "A/B.C/D".count(".")
1
>>> "A/B.C/D".count(".") == 1
True
>>> 
Score: 2

You can use:

re.search('^[^.]*\.?[^.]*$', 'this.is') != None

>>> re.search('^[^.]*\.?[^.]*$', 'thisis') != None
True
>>> re.search('^[^.]*\.?[^.]*$', 'this.is') != None
True
>>> re.search('^[^.]*\.?[^.]*$', 'this..is') != None
False

(Matches period zero or one 1 times.)

Score: 0

While period is special char it must be 3 escaped. So "\.+" should work.

EDIT:

Use 2 '?' instead of '+' to match one or zero 1 repetitions. Have a look at: re — Regular expression operations

Score: 0

If the period should exist only once in 6 the entire string, then use the ? operator:

^[^.]*\.?[^.]*$

Breaking 5 this down:

  1. ^ matches the beginning of the string
  2. [^.] matches zero or more characters that are not periods
  3. \.? matches the period character (must be escaped with \ as it's a reserved char) exactly 0 or 1 times
  4. [^.]* is the same pattern used in 2 above
  5. $ matches the end of the string

As an aside, personally I wouldn't 4 use a regular expression for this (unless 3 I was checking other aspects of the string 2 for validity too). I would just use the 1 count function.

Score: 0

Why do you need to check? If you have a 3 number in a string, I now guess you will 2 want to handle it as a number soon. Perhaps 1 you can do this without Looking Before You Leap:

try:
  value = float(input_str)
except ValueError:
  ...
else:
  ...

More Related questions