Regular Expression python
时间: 2025-06-21 13:28:31 浏览: 5
### 正则表达式简介
正则表达式是一种强大的工具,用于字符串匹配和操作。然而,在某些情况下其行为可能不如预期那样直观[^1]。
#### 基本字符匹配
最简单的正则表达式由单个字面量字符组成。除了特殊的元字符`*+?()|`外,大多数字符都会按原义进行匹配。为了匹配这些元字符本身,则需要用反斜杠`\`对其进行转义,例如`\+`表示匹配一个实际存在的加号[^3]。
```python
import re
pattern = r'\+' # 匹配 '+' 字符
string_with_plus = "The result is 2 + 2."
match_result = re.search(pattern, string_with_plus)
if match_result:
print(f"Found '{match_result.group(0)}' at position {match_result.start()}") # Found '+' at position 14
else:
print("No match found.")
```
#### 使用预定义字符集
有时需要查找特定类型的字符而不仅仅是具体的字母或符号。可以利用预定义好的字符集合简化模式构建过程:
- `\d`: 数字 `[0-9]`
- `\w`: 单词字符(字母、数字及下划线)
- `\s`: 空白字符(空格、制表符等)
```python
text = "Price: $123.45"
price_pattern = r"\$\d+\.\d{2}" # 查找形如$123.45的价格格式
result = re.findall(price_pattern, text)
print(result) # ['\$123.45']
```
#### 定位与边界条件
当希望限定某个子串位于整个输入序列的开头或结尾时,可借助锚点实现精确控制:
- `^`: 行首位置
- `$`: 行尾位置
```python
line_starting_with_hello = "^hello world!"
starts_with_hello = re.match(r"^hello", line_starting_with_hello)
ends_with_world = re.search(r"world!$", line_starting_with_hello)
if starts_with_hello and ends_with_world:
print("Line matches both start and end criteria.") # Line matches both start and end criteria.
```
阅读全文
相关推荐















