Amount of repetitions of symbols in Lua pattern setup

前端 未结 1 1410
遥遥无期
遥遥无期 2021-01-13 04:17

I\'m looking for amount of repetitions of symbols in Lua pattern setup. I try to check amount of symbols in a string. As I read in manual, Even with character classes this

相关标签:
1条回答
  • 2021-01-13 04:37

    We can't but admit that Lua regex quantifiers are very limited in functionality.

    1. They are just those 4 you mentioned (+, -, * and ?)
    2. No limiting quantifier support (the ones you require)
    3. Unlike some other systems, in Lua a modifier can only be applied to a character class; there is no way to group patterns under a modifier (see source). Unfortunately Lua patterns do not support this ('(foo)+' or '(foo|bar)'), only single characters can be repeated or chosen between, not sub-patterns or strings.

    As a "work-around", in order to use limiting quantifiers and all other PCRE regex perks, you can use rex_pcre library.

    Or, as @moteus suggests, a partial workaround to "emulate" limiting quantifiers having just the lower bound, just repeat the pattern to match it several times and apply the available Lua quantifier to the last one. E.g. to match 3 or more occurrences of a pattern:

    local np = 'abc_123'
    local a = np:match('^[a-zA-Z0-9_][a-zA-Z0-9_][a-zA-Z0-9_]+$' )
    

    See IDEONE demo

    Another library to consider instead of PCRE is Lpeg.

    0 讨论(0)
提交回复
热议问题