I am using RegEx to assert the response of an API call, but it’s currently a little too ‘greedy’ and ends up matching all kinds of responses. The RegEx bits are needed since the actual IDs in the response will be different each time.
The RegEx assertion is this:
{data:\[{"name":"Mat","~id":"(.*)"},{"name":"Laurie","~id":"(.*)"}\]},"something":true}
Which matches this correct response:
{data:[{"name":"Mat","~id":"4fd5ec146fc2ee0fff234234"},{"name":"Laurie","~id":"4fd5ec146fc2ee0fff234227"}]},"something":true}
as well as this incorrect response:
{data:[{"name":"Mat","~id":"4fd5ec146fc2ee0fff234234"},{"name":"Laurie","~id":"4fd5ec146fc2ee0fff234227"},{"name":"John","~id":"4fd5ec146fc2ee0fff234237"},{"name":"Paul","~id":"4fd5ec146fc2ee0fff234238"},{"name":"George","~id":"4fd5ec146fc2ee0fff234239"}]},"something":true}
The second (.*) is not just matching the ID of the second item, but it’s matching the ID and all the other unwanted objects.
So I guess I need to make my RegEx be a little more strict when it comes to the ~id fields. Since the IDs will always be 24 hex characters, I’d like to replace the (.*) with something more appropriate.
- I am writing this in Go, and therefore using Go’s RegExp package.
- And am using http://regexpal.com/ to test the RegEx
You can use
[^"]*,[^"]{24}or[0-9a-fA-F]{24}instead of.*for your ID fields.