1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Hummus
  • 559
  • 1
  • 9
  • 21

1 Answers1

1

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).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks, that's almost good, it does the trick but I have errors when the phrase contains brackets. for example, if the string to match is: `Incompatible device (connection error) (x3)` then the number is not captured as a group (cause I don't have any ';' character after it). Any ideas of how to address this issue? – Hummus Feb 15 '15 at 15:05
  • 1
    @AndroidNewbie Add a reluctant qualifier after `[^;]+`, i.e. make it `[^;]+?`. – Sergey Kalinichenko Feb 15 '15 at 16:02