Reputation: 9728
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.
Upvotes: 2
Views: 6909
Reputation: 67968
(?:\[[^\]]*\]\K)?.+$
You can try this.See demo.
https://regex101.com/r/wX9fR1/14
or
\[[^\]]*\](*SKIP)(*F)|.+$
See demo.
https://regex101.com/r/wX9fR1/15
Upvotes: 2
Reputation: 336258
The simplest way would be to use
[^\[\]]*$
which matches any number of characters except brackets until the end of the string. It would also match xxx
in ][]sd[][xxx
, though, so if you need to validate the structure of the string, this regex is not specific enough.
Upvotes: 1
Reputation: 4659
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.
Upvotes: 5