Examples of common regular expressions in python


1. 检查邮件地址是否有效:
```python
import re

email = "[email protected]"

pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

if re.match(pattern, email):
    print("Valid email address")
else:
    print("Invalid email address")
```

2. 验证美国电话号码格式:
```python
import re

phone_number = "123-456-7890"

pattern = r'^\d{3}-\d{3}-\d{4}$'

if re.match(pattern, phone_number):
    print("Valid phone number")
else:
    print("Invalid phone number")
```

3. 提取URL中的域名:
```python
import re

url = "http://www.####.com"

pattern = r'https?://([\w.-]+)'

domain = re.findall(pattern, url)
print("Domain:", domain[0])
```

4. 验证IP地址格式:
```python
import re

ip_address = "192.168.0.1"

pattern = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'

if re.match(pattern, ip_address):
    print("Valid IP address")
else:
    print("Invalid IP address")
```

5. 提取字符串中的所有单词:
```python
import re

text = "Hello, this is a sample text."

pattern = r'\b\w+\b'

words = re.findall(pattern, text)
print("Words found:", words)
```

6. 验证信用卡号是否有效:
```python
import re

credit_card = "1234 5678 9012 3456"

pattern = r'^(\d{4}[\s-]?){3}\d{4}$'

if re.match(pattern, credit_card):
    print("Valid credit card number")
else:
    print("Invalid credit card number")
```

7. 替换字符串中的特殊字符:
```python
import re

text = "This is @sample# text!"

pattern = r'[@#]'

clean_text = re.sub(pattern, '', text)
print("Cleaned text:", clean_text)
```

8. 验证日期格式是否为YYYY-MM-DD:
```python
import re

date = "2022-12-31"

pattern = r'^\d{4}-\d{2}-\d{2}$'

if re.match(pattern, date):
    print("Valid date format")
else:
    print("Invalid date format")
```

9. 验证字符串是否包含至少一个汉字:
```python
import re

text = "Hello 你好 World"

pattern = r'[\u4e00-\u9fa5]+'

if re.search(pattern, text):
    print("String contains a Chinese character")
else:
    print("String does not contain a Chinese character")
```

10. 提取HTML中的图片链接:
```python
import re

html = '<img src="image.jpg" alt="Image"> <img src="picture.jpg" alt="Picture">'

pattern = r'src="([^"]+)"'

image_links = re.findall(pattern, html)
print("Image links found:", image_links)
```

11. 验证字符串是否包含重复的单词:
```python
import re

text = "Hello hello World world"

pattern = r'\b(\w+)\b.*\b\1\b'

if re.search(pattern, text, flags=re.IGNORECASE):
    print("String contains duplicate words")
else:
    print("String does not contain duplicate words")
```

希望这些正则表达式示例对你有所帮助!

Guess you like

Origin blog.csdn.net/qq_26429153/article/details/131813418