【问题标题】:Anyway to separate at whitespaces but avoid separating at file paths?无论如何要在空格处分隔但避免在文件路径处分隔?
【发布时间】:2022-01-24 04:33:12
【问题描述】:

我正在尝试使用regex 将此字符串分隔成一个列表:

-y -hwaccel cuda -threads 8 -loglevel error -hide_banner -stats -i - -c:v hevc_nvenc -rc constqp -preset p7 -qp 18 C:\Users\User\Documents\Python\Smoothie\test 124\Resampled_vid.mp4

我是用下面的方法来分隔的:

split(r'(?!\\)'+'\s+',f"{Settings[1]}".format(Input=InFile,Output=OutFile))

Output:
['-y', '-hwaccel', 'cuda', '-threads', '8', '-loglevel', 'error', '-hide_banner', '-stats', '-i', '-', '-c:v', 'hevc_nvenc', '-rc', 'constqp', '-preset', 'p7', '-qp', '18', 'C:\\Users\\User\\Documents\\Python\\Smoothie\\test', '124\\Resampled_vid.mp4']

期望的输出:

['-y', '-hwaccel', 'cuda', '-threads', '8', '-loglevel', 'error', '-hide_banner', '-stats', '-i', '-', '-c:v', 'hevc_nvenc', '-rc', 'constqp', '-preset', 'p7', '-qp', '18', 'C:\\Users\\User\\Documents\\Python\\Smoothie\\test 124\\Resampled_vid.mp4']

无论如何,我可以完全避免在文件路径处拆分?

【问题讨论】:

  • 你需要一个解析器,而不是一个正则表达式。
  • 文件路径总是在字符串的末尾吗?
  • 不,它可以在字符串中的任何位置。

标签: python regex list split whitespace


【解决方案1】:

我会在这里使用re.findall 方法:

inp = "-y -hwaccel cuda -threads 8 -loglevel error -hide_banner -stats -i - -c:v hevc_nvenc -rc constqp -preset p7 -qp 18 C:\Users\User\Documents\Python\Smoothie\test 124\Resampled_vid.mp4"
parts = re.findall(r'[A-Z]+:(?:\\[^\\]+)+\.\w+|\S+', inp)
print(parts)

['-y', '-hwaccel', 'cuda', '-threads', '8', '-loglevel', 'error', '-hide_banner',
 '-stats', '-i', '-', '-c:v', 'hevc_nvenc', '-rc', 'constqp', '-preset', 'p7',
 '-qp', '18',
 'C:\\Users\\User\\Documents\\Python\\Smoothie\test 124\\Resampled_vid.mp4']

这里使用的正则表达式模式表示匹配,或者:

[A-Z]+:(?:\\[^\\]+)+\.\w+  a file path
|                          OR
\S+                        any group of non whitespace characters

这里的诀窍是首先急切地尝试匹配文件路径。只有失败了,我们才会尝试一次匹配一个单词/术语。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多