正则表达式 - 跳绳

时间:2013-02-22 00:27:49

标签: regex

我正在使用名为https://code.google.com/p/slre/的基本正则表达式解析器,它具有一些基本的正则表集实现。我想解析看起来像

的http标头
GET /3397557/RSVP006_male_468X60_05.swf HTTP/1.1
User-Agent: Opera/9.80 (Macintosh; Intel Mac OS X 10.8.2) Presto/2.12.388 Version/12.10
Host: s0.2mdn.net

我的目的是到达“主持人:”,我对用户代理:行没有打扰,那么如何跳过用户代理行并转移到主机:?我到目前为止尝试的表达方式很无用,

"^\\s*(GET|POST)\\s+(\\S+)\\s+HTTP/(\\d)\\.(\\d)\\s+User-Agent:\\s+.*?\\s+Host:\\s+(\\S+)"

我知道User-Agent:\\s+.*?不是我们如何跳过这条线,但我不知道该怎么做,有什么帮助?

1 个答案:

答案 0 :(得分:0)

我对你的库不熟悉,但下面的正则表达式有效(用javascript实现)

var str = "GET /3397557/RSVP006_male_468X60_05.swf HTTP/1.1"+
"User-Agent: Opera/9.80 (Macintosh; Intel Mac OS X 10.8.2) Presto/2.12.388 Version/12.10"+
"Host: s0.2mdn.net"

// capture the `Host` value
// has `m` flag to ensure multi-line capturing - not sure if you need to do that with
// your library, or even how to do that
var m = str.match(/Host:\s*(.+)/m)
// get the first captured match, which is the value of the `Host` field
console.log(m[1])

编辑:更加谨慎的正则表达式

  • 为字符串添加了换行符(忘记了javascript需要明确添加它们)
  • 在正则表达式的开头添加了start marker^),因此仅在Host:位于行的开头时匹配
var str = "GET /3397557/RSVP006_male_468X60_05.swf HTTP/1.1\n"+
"User-Agent: Opera/9.80 (Macintosh; Intel Mac OS X 10.8.2) Presto/2.12.388 Version/12.10\n"+
"Host: s0.2mdn.net"

var m
if(m = str.match(/^Host:\s*(.+)/m)) // added `[\r\n]+`
  console.log(m[1]) // only if there is a match...