首页 > 解决方案 > 具有固定长度字符串前瞻的正则表达式

问题描述

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

有人也可以解释一下吗?

标签: python-3.xregexregex-lookarounds

解决方案


您可以使用

^(?!.*\\\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

推荐阅读