【问题标题】:Find start and end position of a match in a string在字符串中查找匹配项的开始和结束位置
【发布时间】:2019-02-21 13:42:34
【问题描述】:

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

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

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

【问题讨论】:

    标签: string lua lua-patterns


    【解决方案1】:

    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
    • @user6465354:那是因为这就是你的比赛所说的。您匹配了任意长的字符序列,以“A”结尾。
    • @user6465354:查看我的更新以获取固定模式匹配。
    • 好奇#match,为什么你更喜欢final = start + (#match - 1)而不是_,final, _ = str:find("(A+)[^A]*$")
    • @wsha:因为find 总是返回 pattern 的区域,而不是该模式内的任何捕获。所以找到的范围将包括任何尾随[^A]s。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 2021-04-04
      相关资源
      最近更新 更多