python正则表达式练习题
时间: 2023-10-25 16:09:34 浏览: 107
1. 匹配以hello开头的字符串。
```python
import re
pattern = "^hello"
string = "hello world"
result = re.match(pattern, string)
if result:
print("Matched")
else:
print("Not matched")
```
2. 匹配以world结尾的字符串。
```python
import re
pattern = "world$"
string = "hello world"
result = re.search(pattern, string)
if result:
print("Matched")
else:
print("Not matched")
```
3. 匹配包含数字的字符串。
```python
import re
pattern = "\d+"
string = "abc123def456"
result = re.findall(pattern, string)
print(result)
```
4. 匹配只包含数字的字符串。
```python
import re
pattern = "^\d+$"
string = "123456"
result = re.match(pattern, string)
if result:
print("Matched")
else:
print("Not matched")
```
5. 匹配包含字母和数字的字符串。
```python
import re
pattern = "[a-zA-Z0-9]+"
string = "abc123def456"
result = re.findall(pattern, string)
print(result)
```
6. 匹配只包含字母和数字的字符串。
```python
import re
pattern = "^[a-zA-Z0-9]+$"
string = "abc123"
result = re.match(pattern, string)
if result:
print("Matched")
else:
print("Not matched")
```
7. 匹配包含特殊字符的字符串。
```python
import re
pattern = "[^a-zA-Z0-9\s]+"
string = "abc!@#def$%^"
result = re.findall(pattern, string)
print(result)
```
8. 匹配只包含特殊字符的字符串。
```python
import re
pattern = "^[^a-zA-Z0-9\s]+$"
string = "!@#$%^&*()"
result = re.match(pattern, string)
if result:
print("Matched")
else:
print("Not matched")
```
9. 匹配邮箱地址。
```python
import re
pattern = "^\w+@\w+\.\w+$"
string = "example@gmail.com"
result = re.match(pattern, string)
if result:
print("Matched")
else:
print("Not matched")
```
10. 匹配手机号码。
```python
import re
pattern = "^1[3-9]\d{9}$"
string = "13812345678"
result = re.match(pattern, string)
if result:
print("Matched")
else:
print("Not matched")
```
阅读全文