简体   繁体   English

Lua模式括号和0或1次出现

[英]Lua pattern parentheses and 0 or 1 occurrence

I'm trying to match a string against a pattern, but there's one thing I haven't managed to figure out. 我正在尝试将字符串与模式匹配,但有一件事我还没弄清楚。 In a regex I'd do this: 在正则表达式中我会这样做:

Strings:
en
eng
engl
engli
englis
english

Pattern:
^en(g(l(i(s(h?)?)?)?)?)?$

I want all strings to be a match. 我希望所有的字符串都匹配。 In Lua pattern matching I can't get this to work. 在Lua模式匹配中,我无法使其工作。

Even a simpler example like this won't work: 即使是这样一个更简单的例子也行不通:

Strings:
fly
flying

Pattern:
^fly(ing)?$

Does anybody know how to do this? 有人知道怎么做这个吗?

You can't make match-groups optional (or repeat them) using Lua's quantifiers ? 你不能使用Lua的量词使匹配组可选(或重复它们) ? , * , + and - . *+-

In the pattern (%d+)? 在模式(%d+)? , the question mark "looses" its special meaning and will simply match the literal ? ,问号“失去”其特殊含义,并将简单地匹配文字? as you can see by executing the following lines of code: 正如你可以通过执行以下代码行看到的:

text = "a?"
first_match = text:match("((%w+)?)")
print(first_match)

which will print: 将打印:

a?

AFAIK, the closest you can come in Lua would be to use the pattern: AFAIK,你最接近Lua的将是使用这种模式:

^eng?l?i?s?h?$

which (of course) matches string like "enh" , "enls" , ... as well. 其中(当然)匹配"enh""enls"等字符串。

In Lua, the parentheses are only used for capturing. 在Lua中,括号仅用于捕获。 They don't create atoms. 它们不会产生原子。

The closest you can get to the patterns you want is: 你可以得到你想要的模式最接近的是:

'^flyi?n?g?$'
'^en?g?l?i?s?h?$'

If you need the full power of a regular expression engine, there are bindings to common engines available for Lua. 如果您需要正则表达式引擎的全部功能,则可以使用Lua可用的公共引擎。 There's also LPeg, a library for creating PEGs , which comes with a regular expression engine as an example (not sure how powerful it is). 还有LPeg,一个用于创建PEG的库,它以一个正则表达式引擎为例(不确定它有多强大)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM