正则表达式跳过类似的结果
问题描述:
我一直在想出一种方法来解决我正在通过PCAP文件搜索的情况。在HTTP OK响应之后,我正在寻找标题“Content-Type:。*”。然而,在这样一个例子:正则表达式跳过类似的结果
HTTP/1.1 200 OK
date:
asdf
X-Content-Type: aadsf
Content-Type: application/json
more: stuff
HTTP/1.1 200 OK
date:
asdf
X-Content-Type: aadsf
Content-Type: application/json
more: stuff
我现在的正则表达式"HTTP\/1.1 200 OK[\s\S]*?Content-Type:.*"
在X-Content-Type: aadsf
停止捕获组。我的意图是正则表达式捕获组去Content-Type: application/json
。
任何正则表达式向导,可以给我一些指针?
答
一个PCRE正则表达式没有,你可以使用lookarounds是
见regex demo。如果你想让它更有效率,replace the first .+
with .++
。它可以很容易地与捕获组使用重写,说(CR)LF结束:
^HTTP.*(?:\r?\n.+)*?\r?\nContent-Type:\s*(.+)
注意m
多修改,使线路的^
比赛开始可能仍然是必要的。
详细:
-
^
- 一个子 -
.*
- - 行 -
(?:\R.+)*?
的其余部分 - 任何0+,尽可能少的线路 -
HTTP
开始,换行符(\R
或\r?\n
)的序列后跟1个或多个换行符以外的字符 -
\R
- 换行符 -
Content-Type:
- 文字串 -
\s*
- 0+空格 -
\K
- 匹配复位操作者丢弃来自当前匹配值为止匹配所有文本 -
.+
- 1或除了换行符以外,还有更多的字符。
+0
非常好(+1),与我的相比,这大大减少了步骤。 – Jan
答
你可以使用
^HTTP # match HTTP at the start of the line
(?s:(?!^$).)+? # anything lazily, do not overrun an empty newline
^Content-Type:\s* # Content-Type: at the start of a line
(?P<type>.+) # capture the type
您在这里使用哪种语言? – Jan