我有以下命令:
var re = /^(post|merge|delete) (\/WcfDataService1\.svc\/)(.*) HTTP\/1.1$[\s\S]*?(^{.+\}$)/im
这用于匹配批处理请求中的各种项:
--batchitems
Content-Type: application/http
Content-Transfer-Encoding: binary
POST /WcfDataService1.svc/Orders(123) HTTP/1.1
{"OrderID":"x58"}
这个很好用!执行re.match(str);
时,将返回一个数组,如下所示:
[
'POST',
'/WcfDataService1.svc/',
'Orders(123)',
'{"OrderID":"x58"}'
]
但是,我希望JSON字符串在regex中是可选的,因为它并不总是存在的;例如:
--batchitems
Content-Type: application/http
Content-Transfer-Encoding: binary
DELETE /WcfDataService1.svc/Orders(123) HTTP/1.1
// EOL here
但是我的正则表达式在这里失败了,因为它试图匹配花括号,却找不到它们,所以整个正则表达式都失败了。
如何使(^{.+\}$)
可选(出现0或1次)?我试过(^{.+\}$){0,1}
,但不起作用。
有什么想法吗?
见:https://regex101.com/r/pT3fG0/2和https://regex101.com/r/nO8xZ7/1
https://stackoverflow.com/questions/32123329
复制相似问题