RegEx: Smallest possible match or nongreedy match

后端 未结 3 677
栀梦
栀梦 2020-11-27 02:56

How do I tell RegEx (.NET version) to get the smallest valid match instead of the largest?

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 03:33

    The non greedy operator does not mean the shortest possible match:

    abcabk

    a.+?k will match the entire string (in this example) instead of only the last three signs.

    I'd like to actually find the smallest possible match instead.

    That is that last possible match for 'a' to still allow all matches for k.

    I guess the only way to do that is to make use of an expression like:

    a[^a]+?k
    

    const haystack = 'abcabkbk';
    const paternNonGreedy = /a.+?k/;
    const paternShortest = /a[^a]+?k/;
    
    const matchesNonGreedy = haystack.match(paternNonGreedy);
    const matchesShortest = haystack.match(paternShortest);
    
    console.log('non greedy: ',matchesNonGreedy[0]);
    console.log('shortest: ', matchesShortest[0]);

提交回复
热议问题