python-3.x - 具有固定长度字符串前瞻的正则表达式
问题描述
strings = [
r"C:\Photos\Selfies\1|",
r"C:\HDPhotos\Landscapes\2|",
r"C:\Filters\Pics\12345678|",
r"C:\Filters\Pics2\00000000|",
r"C:\Filters\Pics2\00000000|XAV7"
]
for string in strings:
matchptrn = re.match(r"(?P<file_path>.*)(?!\d{8})", string)
if matchptrn:
print("FILE PATH = "+matchptrn.group('file_path'))
我试图让这个正则表达式以我想的方式工作。大多数网站上的 Look Aheads 示例似乎是非常基本的字符串匹配,即不匹配 'bar',如果它前面有一个 'foo' 作为否定查找的示例。
我的目标是仅当字符串在管道符号之前没有 8 个字符长度的数字并匹配另一个组中管道符号之后的任何内容时才在组中捕获file_path
实际文件路径(我还没有在这里实现) .|
所以在上面的例子中,它应该只匹配前两个字符串
C:\Photos\Selfies\1
C:\HDPhotos\Landscapes\2
如果是最后一个字符串
C:\Filters\Pics2\00000000|XAV7
我想匹配C:\Filters\Pics2\00000000
并<file_path>
匹配XAV7
另一个名为 .
(如果我能在负面展望方面得到一些帮助,我可以自己解决这个问题)
目前 <file_path> 匹配所有内容,这是有道理的,因为它是非贪婪的 (.*) 我希望它仅在管道符号之前的字符串的最后一部分不是 8 长度字符时捕获。
粘贴在下面的代码片段的输出
FILE PATH = C:\Photos\Selfies\1|
FILE PATH = C:\HDPhotos\Landscapes\2|
FILE PATH = C:\Filters\Pics\12345678|
FILE PATH = C:\Filters\Pics2\00000000|
FILE PATH = C:\Filters\Pics2\00000000|XAV7
进行此修改\\
matchptrn = re.match(r"(?P<file_path>.*)\\(?!\d{8})", string)
if matchptrn:
print("FILE PATH = "+matchptrn.group('file_path'))
使事情变得更糟,因为输出是
FILE PATH = C:\Photos\Selfies
FILE PATH = C:\HDPhotos\Landscapes
FILE PATH = C:\Filters
FILE PATH = C:\Filters
FILE PATH = C:\Filters
有人也可以解释一下吗?
解决方案
您可以使用
^(?!.*\\\d{8}\|$)(?P<file_path>.*)\|(?P<suffix>.*)
请参阅正则表达式演示。
细节
^
- 字符串的开头(?!.*\\\d{8}\|$)
\
- 如果字符串包含后跟八位数字,然后|
在字符串末尾,则匹配失败(?P<file_path>.*)
- 组“file_path”:尽可能多的除换行符以外的任何零个或多个字符\|
- 管道(?P<suffix>.*)
- 组“后缀”:字符串的其余部分,除换行符之外的任何零个或多个字符,尽可能多。
请参阅Python 演示:
import re
strings = [
r"C:\Photos\Selfies\1|",
r"C:\HDPhotos\Landscapes\2|",
r"C:\Filters\Pics\12345678|",
r"C:\Filters\Pics2\00000000|",
r"C:\Filters\Pics2\00000000|XAV7"
]
for string in strings:
matchptrn = re.match(r"(?!.*\\\d{8}\|$)(?P<file_path>.*)\|(?P<suffix>.*)", string)
if matchptrn:
print("FILE PATH = {}, SUFFIX = {}".format(*matchptrn.groups()))
输出:
FILE PATH = C:\Photos\Selfies\1, SUFFIX =
FILE PATH = C:\HDPhotos\Landscapes\2, SUFFIX =
FILE PATH = C:\Filters\Pics2\00000000, SUFFIX = XAV7
推荐阅读
- java - 使用 cache-image 选项进行包构建时出错
- python - Python:正则表达式代码无法从文本中删除 ' 和 -
- regex - 具有许多重复空格的正则表达式捕获组
- c++ - 使用 OpenMP 和 GCC 构建静态库和应用程序
- python - 为什么我的数据没有绘制到我的 pcolor 图中?
- c# - Acumatica 扩展库 - 无法加载项目
- excel - 如何使用 Excel VBA 输出特定数据并将它们连接到一个新列中?
- angular - Angular App 在空闲几个小时后发出重复的 http 请求
- webpack - 具有单一入口点的 webpack-hot-middleware 设置
- azure - Azure Devops 代理性能