带有Lua模式匹配的可选组捕获 [英] Optional Group Capture with Lua Pattern Matching

查看:79
本文介绍了带有Lua模式匹配的可选组捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用简单的模式匹配来解析Lua中的化学式.但是,我不知道如何将捕获组指定为可选.这是我想出的模式:

I am trying to parse chemical formulas in Lua using simple pattern matching. However, I do not know how to specify a capture group as being optional. Here is the pattern I have come up with:

pattern = "(%u%l*)(%d*)"

第一组捕获原子符号(即"H","He"等),第二组捕获分子中该原子的数目.此值通常是整数值,但如果为1,则通常将其省略,例如:

The first group captures the atomic symbol (i.e. "H", "He", etc..) and the second group captures the number of that atom in the molecule. This value is usually an integer value, but if it is 1, it is often omitted, such as in:

formula = "C2H6O"

当我尝试进行全局匹配时,如果没有匹配项,则count的结果为'',而不是我期望的nil.

When I attempt to do a global match, if there is no match the result of count is '' instead of what I would anticipate of nil.

compound = {}
for atom,count in string.gmatch(formula, pattern) do
    compound[atom] = count or 1
end

很明显,我只能检查count = '',但是我很好奇Lua中是否有一个可选的捕获组.

Obviously I could just check if count = ''but I was curious if there was an optional capturing group in Lua.

推荐答案

如果Lua中有一个可选的捕获组.

if there was an optional capturing group in Lua.

否; 模式项不会将捕获内容列为可接受的选项,因此您例如,不能像在Perl中那样具有(%d*)?.

No; pattern items don't list captures as acceptable options, so you can't have, for example, (%d*)? like you'd do in Perl.

这篇关于带有Lua模式匹配的可选组捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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