此脚本的re.search()中的正则表达式做什么?

时间:2019-09-23 13:08:29

标签: python regex

我希望有人可以帮助我处理此代码,我期待使用它。

# Absolute path of the script:
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))

# Real path of the script:
REAL_DIR = re.search(r'(?<=\[)(.*?)(?=\])', 
                     subprocess.check_output('dir {} /al | findstr "<JUNCTION>" | findstr Ducati'.format(ROOT_DIR.replace("Ducati", "")), stderr=subprocess.STDOUT, shell=True).decode('ASCII')).group()

# Absolute path of the sandbox
SANDBOX_DIR = os.path.abspath(os.path.join(REAL_DIR, '..', '..'))

# Simple FlashTool Path
FLASHTOOL_DIR = os.path.abspath(
    os.path.join(SANDBOX_DIR, 'DevelopmentEnvironmentPlatformTools', 'Tool.UDSFlashtool',
                'build', 'INSTALL', 'flashtool', 'bin', 'simple-flashtool.exe'))

# Network config file
CONF_DIR_PATH = os.path.abspath(os.path.join(FLASHTOOL_DIR, '..', '..', 'conf'))

# Log file path
LOG_ROOT_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(ROOT_DIR))), 'tta_logs', 'FlashTool')

尤其是这部分

# Real path of the script:
REAL_DIR = re.search(r'(?<=\[)(.*?)(?=\])', 
                     subprocess.check_output('dir {} /al | findstr "<JUNCTION>" | findstr Ducati'.format(ROOT_DIR.replace("Ducati", "")), stderr=subprocess.STDOUT, shell=True).decode('ASCII')).group()

1 个答案:

答案 0 :(得分:1)

如果您要特别询问正则表达式re.search(r'(?<=\[)(.*?)(?=\])'的作用,它将发现用方括号括起来的字符串并在括号内捕获内容。

  • (?<=\[)是令人反感的,断言在这场比赛之前,有一个方括号[
  • (.*?)是一个捕获组,可以多次选择任何字符,但是?量词意味着它捕获的字符越少越好。这意味着它通常不会在其前面捕获右方括号;如果您有a[s]df[ghj]kl,它将捕获sghj而不是s]df[ghj
  • (?=\])是一个积极的前瞻,他断言在这场比赛之后,有一个方括号]

See it in action here!

我可以对脚本的其余部分做出一些猜测,看起来它正在寻找指向某些内容的符号链接(“快捷方式”)。 dir {} /al的存在使我认为该脚本应该在Windows上运行。 subprocess.check_output()将在其中运行命令字符串,然后将其(可能是多行)输出通过管道传递到正则表达式,然后正则表达式将使用.group()创建其找到的匹配项的元组。