简体   繁体   English

高级Lua模式匹配

[英]Advanced Lua Pattern Matching

I would like to know if either/both of these two scenarios are possible in Lua: 我想知道在Lua中这两种情况中的一种/两种是否都可能:

I have a string that looks like such: some_value=averylongintegervalue 我有一个看起来像这样的字符串: some_value=averylongintegervalue

Say I know there are exactly 21 characters after the = sign in the string, is there a short way to replace the string averylongintegervalue with my own? 说我知道字符串中的=符号后面正好有21个字符,是否有一种averylongintegervalue用我自己的字符串替换averylongintegervalue (ie a simpler way than typing out: string.gsub("some_value=averylongintegervalue", "some_value=.....................", "some_value=anewintegervalue") (即比键入更简单的方法: string.gsub("some_value=averylongintegervalue", "some_value=.....................", "some_value=anewintegervalue")

Say we edit the original string to look like such: some_value=averylongintegervalue& 假设我们将原始字符串编辑为如下形式: some_value=averylongintegervalue&

Assuming we do not know how many characters is after the = sign, is there a way to replace the string in between the some_value= and the & ? 假设我们不知道在=号后面有多少个字符,有没有办法替换some_value=&之间的字符串?

I know this is an oddly specific question but I often find myself needing to perform similar tasks using regex and would like to know how it would be done in Lua using pattern-matching. 我知道这是一个奇怪的特定问题,但我经常发现自己需要使用正则表达式执行类似的任务,并且想知道如何使用模式匹配在Lua中完成该任务。

Yes, you can use something like the following ( %1 refers to the first capture in the pattern, which in this case captures some_value= ): 是的,您可以使用类似以下的内容( %1指的是模式中的第一个捕获,在这种情况下,是捕获some_value= ):

local str = ("some_value=averylongintegervalue"):gsub("(some_value=)[^&]+", "%1replaced")

This should assign some_value=replaced . 这应该分配some_value=replaced

Do you know if it is also possible to replace every character between the = and & with a single character repeated (such as a * symbol repeated 21 times instead of a constant string like replaced)? 您是否知道是否还可以用重复的单个字符替换=和&之间的每个字符(例如,重复21次的*符号,而不是像替换的常量字符串)?

Yes, but you need to use a function: 是的,但是您需要使用一个函数:

local str = ("some_value=averylongintegervalue")
  :gsub("(some_value=)([^&]+)", function(a,b) return a..("#"):rep(#b) end)

This will assign some_value=##################### . 这将分配some_value=##################### If you need to limit this to just one replacement, then add ,1 as the last parameter to gsub (as Wiktor suggested in the comment). 如果您只需要将此替换项限制为一个替换项,则在gsub的最后一个参数中添加,1 (如Wiktor在注释中所建议)。

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

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