I have the following regex:
var re = /^(post|merge|delete) (\/WcfDataService1\.svc\/)(.*) HTTP\/1.1$[\s\S]*?(^{.+\}$)/im
This is used to match various items in a batch request:
--batchitems
Content-Type: application/http
Content-Transfer-Encoding: binary
POST /WcfDataService1.svc/Orders(123) HTTP/1.1
{"OrderID":"x58"}
This works great! When I execute re.match(str);
, I am returned an array as follows:
[
'POST',
'/WcfDataService1.svc/',
'Orders(123)',
'{"OrderID":"x58"}'
]
However, I want the JSON string to be optional in my regex, as it will not always be present; eg:
--batchitems
Content-Type: application/http
Content-Transfer-Encoding: binary
DELETE /WcfDataService1.svc/Orders(123) HTTP/1.1
// EOL here
But my regex fails here because it's trying to match the curly braces and it can't find them, so the entire regex fails.
How to I make (^{.+\\}$)
optional (to appear 0 or 1 times)? I tried (^{.+\\}$){0,1}
but does not work.
Any ideas?
See: https://regex101.com/r/pT3fG0/2 and https://regex101.com/r/nO8xZ7/1
EDIT 1
make the json part optional using ?
, as follows:
^(post|merge|delete) (\/WcfDataService1\.svc\/)(.*) HTTP\/1.1$(?:[\s]*?(^{.+\}$))?
An alternative option could be:
(^(post|merge|delete)\s(\/WcfDataService1\.svc\/)(.*)(HTTP\/1\.1)([\s]*)($|^{.*}))
This works as you are hoping. You can see it here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.