python使用正则表达式判断字符串中“.“后面不是数字的情况
要判断字符串中"."后面的字符不是数字,可以使用正则表达式的负向零宽断言(negative lookahead)。以下是Python代码实现:
import redef is_dot_not_followed_by_digit(s):# 正则表达式解释:# \. - 匹配点号# (?!\d) - 负向零宽断言,表示点号后面不能是数字pattern = r'\.(?!\d)'return bool(re.search(pattern, s))# 测试用例
test_cases = [("abc.def", True), # 点号后面不是数字("abc.123", False), # 点号后面是数字("1.2.3", False), # 第一个点号后面是数字,第二个点号后面不是数字("1.2.a", True), # 点号后面不是数字("no_dot_here", False), # 没有点号(".end", True), # 点号在末尾,后面没有数字("1.0", False), # 点号后面是数字("1.a", True), # 点号后面不是数字
]for s, expected in test_cases:result = is_dot_not_followed_by_digit(s)print(f"'{s}': {'通过' if result == expected else '失败'} (预期: {expected}, 实际: {result})")
代码说明:
-
正则表达式
r'\.(?!\d)'
分解:\.
- 匹配点号字符(需要转义)(?!\d)
- 负向零宽断言,表示"后面不能是数字"
-
re.search()
会在字符串中搜索匹配项,如果找到则返回匹配对象,否则返回None。 -
bool()
将结果转换为布尔值,匹配成功返回True,否则返回False。
变体需求
如果你需要检查字符串中所有点号后面都不是数字(而不仅仅是存在至少一个点号后面不是数字),可以使用:
def all_dots_not_followed_by_digit(s):# 匹配所有点号,且每个点号后面都不是数字# 或者字符串中没有点号(此时也返回True)return bool(re.fullmatch(r'[^.]*|(\.(?!\d)[^.]*)+', s))
或者更简单的版本:
def all_dots_not_followed_by_digit(s):# 查找是否有任何点号后面是数字# 如果没有这样的点号,则返回Truereturn not re.search(r'\.\d', s)
根据你的具体需求选择合适的实现方式。