查找字符串中匹配项的开始和结束位置

时间:2018-09-17 15:20:06

标签: string lua lua-patterns

我一直在尝试为lua中的以下问题找到简单的解决方案: 给定诸如str之类的字符串,获取最后发生的A-mer(A的一个或多个实例)的开始和结束位置。例如。对于字符串str = "123A56AA9",解决方案为start=7finish=8

要获得终点位置,我可以使用: _,finish = str:find(".*A")` -- returns 8

但是我找不到任何解决方案来获得开始位置。这可能吗? 谢谢!

2 个答案:

答案 0 :(得分:3)

string.find 返回比赛的开始和结束位置。因此,起始索引是您忽略的_变量。

您的问题是您的模式实际上与您要寻找的不匹配。如果要最后一个“ A”字符序列,则需要执行其他操作。像这样:

local start, final = 1, 1

while(final)
  local temp_start, temp_final = str:find("A+", end)
  if(temp_start) then
    start, final = temp_start, temp_final
  else
    final = nil
  end
end

一个聪明的,基于模式的方法是这样的:

local start, final, match = str:find("(A+)[^A]*$")
if(start) then
  final = start + (#match - 1)
end

答案 1 :(得分:0)

有很多方法可以解决问题。我喜欢与gmatch合作。 顺便说一句。您已使用end作为变量名。但这是一个保留关键字。

str = "123A56AA9"
for startpos, match, endpos in str:gmatch('()(A+)()[^A]*$') do
    print(startpos, match, endpos-1)
end
相关问题