Search code examples
regexregex-group

Capture everything if delimiter is not found


I have a set of strings:

first part#2nd part
a part
1st part#
#2nd part

If the string has a '#' delimiter, I need to capture all the subsequent characters. If the string has no '#' delimiter, I need to capture every single character within the string. Link to example.

How can I do this?


Solution

  • You may use

    ^(?:[^#]*#)?(.*)$
    

    See the regex demo.

    Details

    • ^ - start of string
    • (?:[^#]*#)? - an optional non-capturing group matching 0 or more chars other than # and then a #
    • (.*) - Group 1: any 0 or more chars other than line break chars, as many as possible
    • $ - end of string.