Lua 模式设置中符号的重复次数 [英] Amount of repetitions of symbols in Lua pattern setup

查看:20
本文介绍了Lua 模式设置中符号的重复次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找 Lua 模式设置中符号的重复次数.我尝试检查字符串中的符号数量.正如我在手册中读到的那样,即使使用字符类,这仍然非常有限,因为我们只能匹配固定长度的字符串.

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 is still very limiting, because we can only match strings with a fixed length.

为了解决这个问题,模式支持这四种重复操作符:

To solve this, patterns support these four repetition operators:

  • '*' 匹配前一个字符(或类)零次或多次,尽可能多.
  • '+' 匹配前一个字符(或类)一次或多次,尽可能多.
  • '-' 匹配前一个字符(或类)零次或多次,尽可能少.
  • '?'将前一个字符(或类)设为可选.

因此,没有关于大括号的信息{}例如,

So, no information about Braces {} e.g.,

{1,10}; {1,}; {10};

不起作用.

local np = '1'
local a =  np:match('^[a-zA-Z0-9_]{1}$' )

返回np = nil.

local np = '1{1}'
local a =  np:match('^[a-zA-Z0-9_]{1}$' )

返回 np = '1{1}' :)

这个 url 说没有这样的魔法符号:

This url says that no such magic symbols:

有些字符,称为魔术字符,在使用时具有特殊含义在模式中使用.魔法字符是

Some characters, called magic characters, have special meanings when used in a pattern. The magic characters are

( ) . % + - * ? [ ^ $

大括号只能用作简单的文本,仅此而已.我对吗?避免这种错误"的最佳方法是什么?

Curly brackets do work only as simple text and no more. Am I right? What is the best way to avoid this 'bug'?

可以阅读大括号的常用用法,例如,此处.

It is possible to read usual usage of braces, for instance, here.

推荐答案

我们不得不承认 Lua 正则表达式量词的功能非常有限.

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

  1. 它们就是你提到的那 4 个(+-*?)
  2. 无限制量词支持(您需要的)
  3. 与其他一些系统不同,在 Lua 中修饰符只能应用于字符类;无法在修饰符下对模式进行分组(参见 source).不幸的是 Lua 模式不支持这个('(foo)+''(foo|bar)'),只能重复或选择单个字符,不能是子模式或字符串.
  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.

作为解决方法",为了使用限制量词和所有其他 PCRE 正则表达式特权,您可以使用 rex_pcre.

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

或者,正如@moteus 建议的那样,部分解决方法模拟"只有下限的限制量词,只需重复模式以匹配它几次并将可用的 Lua 量词应用到最后一个一.例如.匹配模式的 3 次或更多次出现:

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_]+$' )

参见 IDEONE 演示

另一个要考虑而不是 PCRE 的库是 Lpeg.

Another library to consider instead of PCRE is Lpeg.

这篇关于Lua 模式设置中符号的重复次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆