正则表达式 linux文件路径
时间: 2023-12-01 16:43:11 浏览: 387
正则表达式可以用来匹配Linux文件路径。以下是一个例子:
```python
import re
# 匹配以/开头的路径,中间可以包含任意数量的字母、数字、下划线、短横线和点号,以及任意数量的子目录,以/结尾
pattern = r'^\/[\w\-.]+(\/[\w\-.]+)*\/?$'
# 测试路径
path1 = '/usr/local/bin/'
path2 = '/home/user/my file.txt'
path3 = '/home/user/my-file.txt'
path4 = '/home/user/my_file.txt'
path5 = '/home/user/my.file.txt'
path6 = '/home/user/my/file.txt'
path7 = '/home/user/my/file/'
# 匹配路径
match1 = re.match(pattern, path1)
match2 = re.match(pattern, path2)
match3 = re.match(pattern, path3)
match4 = re.match(pattern, path4)
match5 = re.match(pattern, path5)
match6 = re.match(pattern, path6)
match7 = re.match(pattern, path7)
# 输出匹配结果
print(match1) # <re.Match object; span=(0, 16), match='/usr/local/bin/'>
print(match2) # None
print(match3) # <re.Match object; span=(0, 20), match='/home/user/my-file.txt'>
print(match4) # <re.Match object; span=(0, 20), match='/home/user/my_file.txt'>
print(match5) # <re.Match object; span=(0, 20), match='/home/user/my.file.txt'>
print(match6) # <re.Match object; span=(0, 21), match='/home/user/my/file.txt'>
print(match7) # <re.Match object; span=(0, 21), match='/home/user/my/file/'>
```
阅读全文