How to match either a subset (preferred) or the entire string in a regular expression?

I have a line that looks something like this:

"Element 1 | Element 2| Element 3: element 4"

I want to fine-tune the portion of the original line that follows the colon (to the end of the original line), but if there is no colon, I want to capture the whole line.

What I have tried so far are the options around this:

:.*|.*
:?.*

and etc.

However, if they match, if the colon is present or not, they do not prefer the substring when colon is detected.

I played with this at http://regexpal.com .

Ultimately, this will be used in the CMDB tool for CI mapping, so the overall solution would be ideal, not language or engine specific.

+4
source share
2 answers

:

(:.*|[^:]*)$

. DEMO

:

,

  • if
+3

:

(?:^|:)[^:\n]*$

- RegEx

+1

All Articles