【问题标题】:regex: get numbered capture of all numbers in a string正则表达式:获取字符串中所有数字的编号捕获
【发布时间】:2013-03-23 19:53:54
【问题描述】:

如何捕获给定字符串中的所有数字?它们是浮点数、整数、正数还是负数都无关紧要。它应该捕获 50 或 100.25 或 12345678 或 -78.999 每个作为编号捕获。

我的意图是查找并替换字符串中的第 n 个数字(自动热键)。

正则表达式应将所有匹配项捕获到一个数组中。

到目前为止,我已经想出了这个正则表达式(它似乎只捕获了第一个匹配项):

[-+]?\d+(\.\d+)?

这是我的自动热键功能,如果你有兴趣:

ReplaceNumber(whattext, instance, replacewith){
    numpos := regexmatch(whattext, "Ox)[-+]?\d+(\.\d+)?", thisnumber)
    returnthis := thisnumber.value(instance)
    return returnthis
}

【问题讨论】:

    标签: regex autohotkey


    【解决方案1】:

    似乎AutoHotKey uses PCRE,所以下面的正则表达式应该可以完成这项工作:

    [+-]?\d+(?:\.\d+)?

    【讨论】:

    • 匹配,但我不确定它是否是编号捕获。它匹配了 3 次,但不捕获 3 次,因此只返回第一个匹配项。
    • @BGM 我不熟悉autohotkey,但我找到了this post,看起来和你遇到的问题一样,显然你必须做一个循环。
    • Hamza,我已经在逐行循环了。我可以循环整个事情并测试每个字符是否是一个数字,但我不想这样做。
    • Hamza,您在上一条评论中发布的链接有答案 - 那里有一篇帖子,聚乙烯写了一个简短的 grep 函数。该函数,当给定我原始帖子中的正则表达式时,将返回字符串中所有数字的分隔字符串:autohotkey.com/board/topic/… 既然你把我带到了正确的地方,我会标记你的答案,但我会自己发布解决方案。
    • @BGM 不,我认为您应该回答并将其标记为其他访问者的答案!
    【解决方案2】:

    使用聚乙烯的grep 函数,你可以给它一个正则表达式字符串,它会返回一个所有匹配的分隔字符串。然后,您可以用您的字符串替换该数字的确切实例。在this thread(感谢 HamZa DzCyber​​DeV)中,有一个解释为什么会这样。

    (为此您需要grep script!)

    ReplaceNumber(whattext, instance, replacewith){
        numpos := grep(whattext, "[+-]?\d+(?:\.\d+)?",thisnumber,1,0,"|")
        stringsplit, numpos, numpos,|
        stringsplit, thisnumber,thisnumber,|
    
        thispos := numpos%instance%   ;get the position of the capture
        thisinstance := thisnumber%instance%  ;get the capture itself
        thislen := strlen(thisinstance) 
        ;now fetch the string that comes before the named instance
        leftstring := substr(whattext, 1, thispos-1)
        rightstring := substr(whattext, thispos+thislen, strlen(whattext))
    
        returnthis := leftstring . replacewith . rightstring
    
        return returnthis
    }
    msgbox, % replacenumber("7 men swap 55.2 or 55.2 for 100 and -100.", 5, "SWAPPED")
    

    结果:

    ; 1-->  SWAPPED men swap 55.2 for 100 and -100.
    ; 2-->  7 men swap SWAPPED or 55.2 for 100 and -100.
    ; 3 --> 7 men swap 55.2 or SWAPPED for 100 and -100.
    ; 4 --> 7 men swap 55.2 or 55.2 for SWAPPED and -100.
    ; 5 --> 7 men swap 55.2 or 55.2 for 100 and SWAPPED.
    

    谢谢,聚乙烯和哈姆扎!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 2022-10-15
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      相关资源
      最近更新 更多