Search code examples
regexoptional-values

Ignore an optional prefix in expression


How can I get a string after a prefix that is optional? Example:

Expression    Result
------------------------
[asdf]xxx  => xxx
[foo]bar   => bar
[]bla      => bla
test       => test

[...] is the optional part.

Obviously, I need a look-around assertion. But I don't know hot to make it optional.


Solution

  • This is a modification of @Maroun's regex making the [...] optional:

    (?:\[.*?\])?(.+)
    

    https://regex101.com/r/hM2sK8/1

    Notice how I put the first part in a non-capturing group and made it optional with the ? after the group.