Regular expression for a character that appears at most once

I want to check a string containing a period, ".", At most once in python.

+2


source to share


6 answers


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

      

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")

      

+7


source


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
>>> 

      

+5


source


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

      

(Corresponds to period zero or once.)

+2


source


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

0


source


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.

0


source


Why do you need to check? If you have a number in a string, I am now guessing that you will want to treat it as a number soon. Perhaps you can do this without looking before jumping:

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

      

0


source







All Articles