我想使用Regex格式化HTTP标头。我已经使用split(' ')
然后进行了数组操作,但是这次我想使用Regex执行此操作。
我想接受这个输入,这是一个巨大的字符串:
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
并将其格式化为一个对象:
{ 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'
}
我通过使用split
方法理解,我的代码更可读。但是,我的第一个尝试是使用正则态度,因为我的目标是提取/格式化字符串。
我知道通过正则是可能的,但是值得吗?每个人都怎么看?
谢谢您的时间。
这应该对您有用:
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))
/([w-]+): (.*)/g
此正则将匹配任何header-name: value
并像['header-name: value', 'header-name', 'value']
然后,我们将其缩短到headers
对象,其中header-name
为key
,value
为value
最后,我们分析第一行以获取其余信息
它如何工作
(w+)
匹配并捕获1个或更多单词字符
s+
匹配1或更多的空格 (.*?)
匹配并捕获任何char 不裸露 *?
s+
直到找到一个或多个空白
(.*)
匹配evrything(直到线结束)
您可以将.split()
与RegExp
s/
一起使用,其中.split()
返回的数组的前三个元素应为verb
,path
,protocol
;在前三个元素上利用.shift()
,其余的结果将属性设置为属性,使用当前索引在headers
对象和阵列的下一个索引,直到数组.length
在while
loop的条件下评估到false
。
let getHeaders = headers => {
let h = headers.split(/s/);
let o = {
verb: h.shift(),
path: h.shift(),
protocol: h.shift(),
headers: {}
};
while (h.length) {
o.headers[h.shift()] = h.shift();
}
return o
};
var str = `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`;
console.log(getHeaders(str));
这应该有效。
搜索:
(GET)s(.+)s(HTTP/d+.d+)n(Host):s(.+)$n(Cache-Control):s(.+)$n(Postman-Token):s(.+)$
替换为:
{ headers: nt{ $4 '$5',nt '$6': '$7',nt '$8': '$9'nt}, ntverb: '$1',ntpath: '$2',ntprotocol: '$3'n}
JavaScript代码:
const regex = /(GET)s(.+)s(HTTP/d+.d+)n(Host):s(.+)$n(Cache-Control):s(.+)$n(Postman-Token):s(.+)$/gm;
const str = `GET /v1/search?q=bob%20dylan&type=artist HTTP/1.1
Host: api.spotify.com
Cache-Control: no-cache
Postman-Token: e2f09f98-f`;
const subst = `{ headers: nt{ $4 '$5',nt '$6': '$7',nt '$8': '$9'nt}, ntverb: '$1',ntpath: '$2',ntprotocol: '$3'\n}`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
输入:
GET /v1/search?q=bob%20dylan&type=artist HTTP/1.1
Host: api.spotify.com
Cache-Control: no-cache
Postman-Token: e2f09f98-f
输出:
{ headers:
{ Host 'api.spotify.com',
'Cache-Control': 'no-cache',
'Postman-Token': 'e2f09f98-f'
},
verb: 'GET',
path: '/v1/search?q=bob%20dylan&type=artist',
protocol: 'HTTP/1.1'
}
请参阅:https://regex101.com/r/3dkeas/4