Python last character zeo or one time

Viewed 43

Input string could be any of the below strings.

image: xyz.com/elk_init_cos7:1.0.0-20.12.0
image: "xyz.com/ckaf/kafka:4.1.0-5.4.1-59"
import re
mat = re.search("image:\s*\"?(.+?/(.+?):(.+?))\"?", str)
if mat:
    print (mat.group(1))
    print (mat.group(2))
    print (mat.group(3))

Ouptut:

artifactory.net.nokia.com/ckaf/kafka:4
ckaf/kafka
4

If I use regex as "image:\s*"?(.+?/(.+?):(.+))"?", then I am getting the string with double quote 4.1.0-5.4.1-59".

How can I get last part of the string without " coming at end and still satisfy other input string also?

2 Answers

The (.+?))\"? part of the pattern when used at the end of string is matching very few chars because .+? only has to match a single char, then it goes on to check for a ", and if there is no " the single char captured with (.+?). There is no obligation here to proceed matching until a " char.

The (.+))\"? at the end of the pattern will match and capture text up to the end of the line, and \"? will match nothing (or, in other words, empty string).

You want to match anything but a " char, one or more times here.

image:\s*\"?(.+?/(.+?):([^\"]+))

See the regex demo. I added \n at the online demo just to make sure the match does not go across lines, if the line are standalone strings in your real scenario, you do not need it.

You may use the negated character classes in other places of your regex, too:

image:\s*\"?([^/]+/([^:]+):([^\"]+))

See this regex demo.

The [^/]+/([^:]+) part now matches and captures into Group 1 any one or more chars other than / (with ([^/]+)), then matches a / char, and then captures into Group 2 any one or more chars other than a : char (([^:]+)).

re.search("image:\s*\"?(.+?/(.+?):(.+?))\"?$", str)

when I placed $ at the end, it addressed my issue. Thank you for sharing your inputs.

Related