字符最多出现在

2024-03-29 14:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中最多检查一次包含句点“.”的字符串。


Tags: 字符串句点
3条回答
[^.]*\.?[^.]*$

一定要match,不要search

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

编辑

如果只考虑整数和小数,就更简单了:

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

您可以使用:

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

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

(匹配周期0或1次。)

不需要regexp,请参见^{}

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

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. 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
>>> 

相关问题 更多 >