Home > database >  JQ - extract text with multiple regex expressions
JQ - extract text with multiple regex expressions

Time:06-09

I have keys that sometimes looks like this docker/nginx:latest and sometimes looks like this docker/nginx@sha256:9560f8528a3cd

I can extract the image name between the Repo name and tag using the following

.image | match("(?<=\\/)(.*)(?=\\:)").captures[].string 

However how do I add multiple conditions to capture both conditions ?

I have tried this but it doesn't work

.image | match("(?<=\\/)(.*)(?=\\: | \\@)").captures[].string

Sample Json

{
 "image": "docker/nginx:latest"
}

or

{
 "image": "docker/nginx@sha256:9560f8528a3cd"
}

CodePudding user response:

Remove the spaces and make the capture non-greedy by adding a ? to .* (otherwise it will read until the : also in the second case):

.image | match("(?<=\\/)(.*?)(?=\\:|\\@)").captures[].string

Demo

You may also want to remove the escaping where it is not needed:

.image | match("(?<=/)(.*?)(?=:|@)").captures[].string

Demo

CodePudding user response:

You have spaces that shouldn't be there (unless you add the x modifier), but the main issue is .* matches too much.

It was suggested that you replace .* with .*?, but that's a really bad habbit that will bite you one day. You should replace it with [^:@]* instead.

All you need is this:

.image | match("/([^:@] )").captures[].string

Demo on jqplay

  • Related