目标:将bash脚本中的cut命令替换为-d和-f选项。
bash示例:
$ echo the-example-text-with-delimiters | cut -d - -f 2-4
$ example-text-with
$ echo the-example-text-with-delimiters | cut -d - -f 3-5
$ text-with-delimitersRegex似乎是一个显而易见的选择,但我似乎想不出任何简单的解决方案,可以选择一系列领域,就像cut那样。
发布于 2022-01-05 15:45:56
您仍然可以在str.split('-')中使用Regex。
下面是操作步骤:
x = 'the-example-text-with-delimiters'
i,j = 2,4
cut_x = '-'.join(x.split('-')[i-1:j])
print(cut_x)打印的值是:'example-text-with'
发布于 2022-01-05 16:03:11
使用Regex:
\w -匹配任何字母数字字符(数字和字母)
import re
x = 'the-example-text-with-delimiters'
i,j = 2,4
cut_x = '-'.join(re.findall(r'\w+', x)[i-1:j])产出:
'example-text-with'https://stackoverflow.com/questions/70595579
复制相似问题