2

如何捕获给定字符串中的所有数字?它们是浮点数、整数、正数还是负数都无关紧要。它应该捕获 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
}
4

2 回答 2

1

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

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

于 2013-03-23T20:33:31.357 回答
1

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

(为此,您需要grep 脚本!)

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.

谢谢,聚乙烯和哈姆扎!

于 2013-03-23T21:38:25.090 回答