使用正则表达式在Python中匹配文件的开头和结尾

bluesky1年前 ⋅ 118 阅读

ChatGPT的回答仅作参考:

匹配文件开头:

```python
import re

filename = "example.txt"
pattern = r'^\w+'  # 匹配开头的单词字符

match = re.match(pattern, filename)
if match:
    print(match.group(0))  # 输出example
else:
    print("No match")
```

匹配文件结尾:

```python
import re

filename = "example.txt"
pattern = r'\.\w+$'  # 匹配结尾的扩展名

match = re.search(pattern, filename)
if match:
    print(match.group(0))  # 输出.txt
else:
    print("No match")
```

全部评论: 0

    相关推荐