gpt4 book ai didi

regex - 如何在 Bash 中拆分 URL 参数

转载 作者:行者123 更新时间:2023-11-29 09:31:51 25 4
gpt4 key购买 nike

我有这个 Bash 脚本:

#!/bin/bash

rawurldecode() {

# This is perhaps a risky gambit, but since all escape characters must be
# encoded, we can replace %NN with \xNN and pass the lot to printf -b, which
# will decode hex for us

printf -v REPLY '%b' "${1//%/\\x}" # You can either set a return variable (FASTER)

echo "${REPLY}" #+or echo the result (EASIER)... or both... :p
}

echo -e "Content-type: video/x-matroska\n"

arr=(${QUERY_STRING//=/ })
ffmpeg -i "$(rawurldecode ${arr[1]})" -acodec copy -vcodec copy -map 0:0 -map 0:2 -f matroska - 2>/dev/null &
pid=$!
trap "kill $pid" SIGTERM SIGPIPE
wait

我想更改它以便它可以像这样处理查询字符串中的多个参数:

param1=value1&param2=value2&param3=value3

目前 arr 正则表达式拆分是基于 = 所以它只能处理一个参数。我不确定如何更改此正则表达式,所以我得到 arr[1] = value1; arr[2] = value2
理想情况下,我需要它是一个关联数组,例如:arr['param1'] = value1 但我不确定这在 Bash 中是否可行。

其他语言(PHP、Perl、Python)的解决方案是可以接受的,只要脚本的行为保持不变(即它需要获取查询字符串并从标准输出输出 header +输出,并且能够当客户端断开连接时终止它产生的进程)。

也欢迎提出任何有关如何清理此输入的建议。

最佳答案

你可以只更改行:

arr=(${QUERY_STRING//=/ })

与:

arr=(${QUERY_STRING//[=&]/ })

然后你可以在奇数索引中获取你的值。

例子

$ QUERY_STRING='param1=value1&param2=value2&param3=value3'
$ arr=(${QUERY_STRING//[=&]/ })
$ echo ${arr[1]}
value1
$ echo ${arr[3]}
value2
$ echo ${arr[5]}
value3

再次阅读您的问题,我发现您需要后续索引中的值。你可以用 extglob 做到这一点shell选项如下:

shopt -s extglob # with this you enable 'extglob'
arr=${QUERY_STRING//?(&)+([^&=])=/ }

解释:

?(&) -> 匹配零次或一次出现的 &
+([^&=])= -> 匹配 1+ 次不带 &= 后跟 =< 的字符串

关于regex - 如何在 Bash 中拆分 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com