匹配最多出现一次的字符的正则表达式
我想在Python中检查一个字符串,看看里面最多只包含一次句号“.”。
相关问题:
6 个回答
2
你可以使用:
re.search('^[^.]*\.?[^.]*$', 'this.is') != None
>>> re.search('^[^.]*\.?[^.]*$', 'thisis') != None
True
>>> re.search('^[^.]*\.?[^.]*$', 'this.is') != None
True
>>> re.search('^[^.]*\.?[^.]*$', 'this..is') != None
False
(这个可以匹配零次或者一次。)
5
其实不需要用正则表达式,看看这个str.count()就知道了:
str.count(sub[, start[, end]])这个方法会返回在指定范围[start, end]内,子字符串sub出现的次数。可选的参数start和end就像切片那样使用。
>>> "A.B.C.D".count(".")
3
>>> "A/B.C/D".count(".")
1
>>> "A/B.C/D".count(".") == 1
True
>>>
10
[^.]*\.?[^.]*$
>>> 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")
确保使用 match,不要用 search
补充说明:
如果你只考虑整数和小数,那就更简单了: