Python 正则表达式 例子
Python 的 re 模块提供了正则表达式的功能。以下是一些常见的正则表达式例子:
1.匹配字符串中的数字
python
import re
text = "The price is 123 dollars"
pattern = r'\d+'
match = re.search(pattern, text)
if match:
print("Found:", up())
2.匹配地址
python
import re
email = "example@example"
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if re.match(pattern, email):
print("Valid email")
else:
print("Invalid email")
3.匹配日期 (YYYY-MM-DD)
python
import re
date = "2023-10-23"
pattern = r'\b\d{4}-\d{2}-\d{2}\b'
if re.match(pattern, date):
print("Valid date")
else:
print("Invalid date")
4.查所有单词
python
import re
text = "The quick brown fox jumps over the lazy dog"
pattern = r'\b\w+\b'
matches = re.findall(pattern, text)
print(matches) # 输出:['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
5.替换文本中的模式
python
import re
text = "Hello, world! World is beautiful." python正则表达式判断
pattern = r'world'
replacement = 'universe'
new_text = re.sub(pattern, replacement, text, flags=re.IGNORECASE)
print(new_text) # 输出:Hello, universe! Universe is beautiful.
这只是正则表达式在 Python 中的一些基本用法。正则表达式是一个非常强大的工具,可以用于各种复杂的文本处理任务。