Search code examples
goregex-group

Golang Regex not matching the optional part even when it is present in the string


I am trying to parse some output from a command, I want to check if the command had an error in it, so I look for the string **Apply Error**. If there is no error present the previously mentioned string is absent. My regex to match that is (?s)Ran Apply.+?(\*\*Apply Error\*\*)?. I am doing this in Golang

This regex does not work even when the string ** Apply Error** is present in the output, if I remove the last ? in my regex it works as expected. It captures 2 groups with the second being the optional part.

Examples: Case - 1 when the string **Apply Error** is present

Ran Apply for dir: `some random path/something/something`

`**Apply Error**`

Output: Match **Apply Error** and capture it as a group

Case - 2 When **Apply Error** is not present

Ran Apply for dir: `some random path/something/something`
some random text

Output: Match everything as is

Demo: https://regex101.com/r/Um3CNc/1 In the demo even though ** Apply Error** is present it does not match it

How can I match the optional part?


Solution

  • You can use

    (?s)Ran Apply\b(?:.+?(\*\*Apply Error\*\*)|.*)
    

    Explanation

    • (?s) Inline modifier to have the dot match a newline
    • Ran Apply\b Match literally followed by a word boundary
    • (?: Non capture group
    • .+?(\*\*Apply Error\*\*) Match 1+ chars, as few as possible and capture **Apply Error** in group 1
      • | Or
      • .* Match the rest of the text
    • ) Close non capture group

    See a regex demo with Apply Error present and without Apply Error present.