使用正则表达式格式化 HTTP 标头

kdi*_*zle 3 javascript regex string http http-headers

我想使用正则表达式格式化我的 HTTP 标头。我已经使用split(' ')后跟数组操作完成了它,但是这次我想使用正则表达式执行此操作。

我想接受这个输入,它是一个巨大的字符串:

GET /v1/search?q=bob%20dylan&type=artist HTTP/1.1
Host: api.spotify.com
Cache-Control: no-cache
Postman-Token: e2f09f98-f8e0-43f7-5f0e-b16e670399e2
Run Code Online (Sandbox Code Playgroud)

并将其格式化为一个对象,如下所示:

{ headers: 
   { Host: ' api.spotify.com',
     'Cache-Control': ' no-cache',
     'Postman-Token': ' e2f09f98-f8e0-43f7-5f0e-b16e670399e2' 
   },
  verb: 'GET',
  path: '/v1/search?q=bob%20dylan&type=artist',
  protocol: 'HTTP/1.1' 
}
Run Code Online (Sandbox Code Playgroud)

我理解通过使用该split方法,我的代码更具可读性。但是,我的第一次尝试是使用正则表达式,因为我的目标是提取/格式化字符串。

我知道通过正则表达式是可能的,但这是否值得?大家觉得呢?

感谢您的时间。

Mac*_*eja 5

这应该适合你:

const data = `GET /v1/search?q=bob%20dylan&type=artist HTTP/1.1
Host: api.spotify.com
Cache-Control: no-cache
Postman-Token: e2f09f98-f8e0-43f7-5f0e-b16e670399e2`

const format = data => {
    const headers = {}
    const result = { headers }
    const regex = /([\w-]+): (.*)/g
    let temp
    while (temp = regex.exec(data)) {
        headers[temp[1]] = temp[2]
    }
    temp = data.match(/(\w+)\s+(.*?)\s+(.*)/)
    result.verb = temp[1]
    result.path = temp[2]
    result.protocol = temp[3]
    return result
}

console.log(format(data))
Run Code Online (Sandbox Code Playgroud)

/([\w-]+): (.*)/g这个正则表达式将匹配任何header-name: value并像这样捕获它['header-name: value', 'header-name', 'value']

然后我们将它分配给headers对象 where header-nameiskeyvalueisvalue

最后,我们解析第一行以获取其余信息

这个怎么运作

(\w+)匹配和捕获1或多个单词字符
\s+匹配1个或多个空白 (.*?)匹配并捕获任何字符不gready *?
\s+ 直到一个或多个空白空间被发现
(.*)匹配evrything(直至行尾)