简体   繁体   English

用于捕获Curl HTTP状态代码和主体响应的正则表达式

[英]Regex for capturing Curl HTTP Status Code and body response

I'm attempting to create a regex that captures both the HTTP status code as well as the body of a curl request. 我试图创建一个捕获HTTP状态代码以及curl请求主体的正则表达式。 The regex pattern below works on multiple online sites, but won't match in a shell if-statement on my Mac's command line. 下面的正则表达式模式可在多个在线站点上运行,但在Mac的命令行上的shell if语句中无法匹配。 Is my regex off or is there something else going on? 我的正则表达式关闭了吗?

RESPONSE=$(curl -s -i -X GET http://www.google.com/)

# Match and capture the status code, match the headers, match two new lines, match and capture an optional body
re="^HTTP\/\d\.\d\s([\d]{3})[\w\d\s\W\D\S]*[\r\n]{2}([\w\d\s\W\D\S]*)?$"

if [[ "${RESPONSE}" =~ $re ]]; then
  echo "match"
  # Now do stuff with the captured groups, "${BASH_REMATCH[...]}"
else
  echo "no match"
fi

I'm also open to other ways of doing this (I'm targeting a machine running CentOS 5). 我也乐于接受其他方法(我的目标是运行CentOS 5的计算机)。

Same idea as @delarsschneider, slightly less complicated 与@delarsschneider的想法相同,稍微复杂一点

RESPONSE=$(curl -s -i -X GET http://www.google.com/)

CODE=$(echo $RESPONSE | sed -n 's/HTTP.* \(.*\) .*/\1/p')

BODY=$(echo $RESPONSE | tr '\n' ' ' | sed -n 's/.*GMT *\(.*\)/\1/p')

echo $CODE
echo $BODY

Since you are open to other solutions, too, you can try this out. 由于您也可以使用其他解决方案,因此可以尝试一下。

RESPONSE=$(curl -s -i -X GET http://www.google.com/)

HTTP_STATUS_CODE=`echo $RESPONSE | sed '
  /HTTP/ { 
    s/^HTTP[^ ]* //
    s/ .*$//
    q
  }
  D'`

BODY=`echo $RESPONSE | sed '
  /^.$/ {
    :body
    n
    b body
  }
  D'`

echo $HTTP_STATUS_CODE
echo $BODY

HTTP_STATUS_CODE is found in the first line starting with HTTP. 在以HTTP开头的第一行中找到HTTP_STATUS_CODE Every non-space until the first space is removed and from the result ('302 Found') everything from first space till the end of the line is removed. 删除第一个空格之前的每个非空格,并从结果(找到“ 302找到”)中删除从第一个空格到行尾的所有内容。

BODY starts at the first line matching a single char (lines before are deleted with 'D'). BODY从与单个字符匹配的第一行开始(之前的行用'D'删除)。 From here print every line until the end of the input. 从这里开始打印每一行,直到输入结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM