gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
python 写一个匹配整数的正则表达式
- User
python 写一个匹配整数的正则表达式
- Assistant
要在Python中写一个匹配整数的正则表达式,可以使用
re模块。以下是一个示例代码段,它展示了如何编写和使用这样的正则表达式:import re # 正则表达式模式,匹配整数 pattern = r'^-?\d+$' # 测试字符串 test_strings = ['123', '-456', '007', 'abc', '12.34', ''] # 编译正则表达式 compiled_pattern = re.compile(pattern) for s in test_strings: if compiled_pattern.match(s): print(f"'{s}' is a valid integer.") else: print(f"'{s}' is not a valid integer.")解释正则表达式模式
^-?\d+$:^: 匹配字符串的开始。-?: 可选的负号-,表示可能会有负号也可能没有。\d+: 一个或多个数字,\d表示数字字符,+表示一个或多个。$: 匹配字符串的结束。
这个正则表达式确保整个字符串仅包含一个可能的负号后跟一个或多个数字。