I want to have two optional parts in my regex - either of them can be found in matching string, and also both of them can at the same time.
Both of those optional parts consist of a wildcard (I wrote
.* here but it can be say
[a-zA-Z]+; anyway the point is that second part of the regex (
Bar) matches the wildcard if greedy matching is applied).
It's best illustrated by this Firebug output:
>>> /(Foo.*)?(Bar.*)?/.exec("FooAA") ["FooAA", "FooAA", undefined] // OK >>> /(Foo.*)?(Bar.*)?/.exec("BarAA") ["BarAA", undefined, "BarAA"] // OK >>> /(Foo.*)?(Bar.*)?/.exec("FooAABarAA") ["FooAABarAA", "FooAABarAA", undefined] // I'd like to have ["FooAABarAA", "FooAA", "BarAA"]
Is there a way to construct a regex matching my three test cases above?
I can use sth like
but I want to avoid duplication.
You need non-greedy wildcards. This works for me:
You should simply be able to make the first wildcard non-greedy like this: