Search code examples
regexregex-group

non-greedy regex capture groups syntax


given the following text

key: foo/bar:v1.2.3
    key: baz/spam:1.2.3 greedy

i have tried the following regex:

^\s*key: (?<ref>.*?):(?<ver>.*)

which returns the following groups (demo):

  • ref: foo/bar, ver: v1.2.3
  • ref: baz/spam, ver: 1.2.3 greedy

what is missing from the regex in order to match\group the version (e.g. 1.2.3) without the preceding text (e.g. greedy)?


Solution

  • Since you are using .* in your last capture group, it is matching everything till the end of of line in 2nd capture group.

    You could restrict matching of your regex to match only non-whitespace characters by using \S (which is opposite of \s and it matches any character other that whitespaces):

    ^\s*key: (?<ref>[^:]+):(?<ver>\S+)
    

    Also note use of a negated character class [^:] in 1st capture group to reduce backtracking which matches any character other than :.

    RegEx Demo