Variable length look-behind

后端 未结 5 1154
猫巷女王i
猫巷女王i 2020-12-16 13:38

Is there any elegant solution to build a variable length look-behind regex such as this one ?

/(?<=eat_(apple|pear|orange)_)today|yesterday/g;

5条回答
  •  悲&欢浪女
    2020-12-16 14:03

    Use \K as a special case.

    It's a variable length positive lookbehind assertion:

    /eat_(?:apple|pear|orange)_\Ktoday|yesterday/g
    

    Alternatively, you can list out your lookbehind assertions separately:

    /(?:(?<=eat_apple_)|(?<=eat_pear_)|(?<=eat_orange_))today|yesterday/g
    

    However, I would propose that it's going to be a rare problem that could potentially use that feature, but couldn't be rethought to use a combination of other more common regex features.

    In other words, if you get stuck on a specific problem, feel free to share it here, and I'm sure someone can come up with a different (perhaps better) approach.

提交回复
热议问题