Search code examples
regexnon-greedyend-of-line

"Optional" end of line $ literal (non greedy)


I would like to make the "end of line" character ($) "optional" (or non-greedy). Meaning, I want to capture a certain pattern at the end of the line, or none. This is the regex I've built:

(.+\s*)\s*(?:(\(\s*[xX\*]\s*\d+\s*\))|$)

I would like to capture things like

Incompatible device (x10) ; Boot sequence aborted

What i'd want is, to be able to capture the first string here (Incompatible device (x10)), but if the quantifier (x10) does not appear, to be able to capture just the second one (Boot sequence aborted, without a (x##) after it). if I test the pattern on

boot sequence aborted

It does get captured, however, if I test it on the whole string above, everything is captured, and I only need the "Incompatible device" part.


Solution

  • You are really close: all you need is replacing ., which matches any character, with [^;], like this:

    ([^;]+\s*)\s*(?:(\(\s*[xX\*]\s*\d+\s*\))|$)
    

    Now your expression would capture the first part if (x10) is present (demo), or the second part if it is missing (demo).