简体   繁体   中英

Regex - match 0 or 1 times

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"}
  • First group: the type (POST/MERGE/DELETE)
  • Second group: /WcfDataService1.svc/
  • Third group: anything which appears after WcfDataService1.svc, in this instance: Orders(123)
  • Fourth group: the JSON string

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]*?(^{.+\}$))?

DEMO

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM