robsch
robsch

Reputation: 9728

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.

Upvotes: 2

Views: 6909

Answers (3)

vks
vks

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

Tim Pietzcker
Tim Pietzcker

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

asontu
asontu

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

Related Questions