正则表达式匹配指定单词和冒号之后的数字,直到其他字符

regex match numbers after specified word and colon until other characters

A : 10 | B: 2
C: 95 | D: 48

我正在编写一个程序,需要通过其键(A、B、C、D)从字符串中提取数字。例如,query_string("A") 将从字符串中 return 10。现在我想出了这个正则表达式模式,但它只匹配第一个键 A.

(?<=A)*(?<=:)*\d[^\s]

根据@WiktorStribiżew 的要求,这是关于我基本上想做的事情的代码

/*
clipboard =
(
A : 10 | B: 2
C: 95 | D: 48
)
*/

keys := ["A", "B", "C", "D"]
empty := []

query_string(str, key) {
    RegExMatch(str, "O)\b" key "\s*:\s*(\d+)", output)
    return output[1]
}

F1::
for index, key in keys {
    if (query_string(clipboard, key) > 1) {
        send % key
    } else {
        empty.Push(key)
    }
}
return

你可以这样做:

query_string(key, text):
    import re
    result = re.findall('(?:(?:' + key  + ')\s*:\s*)([0-9]*\s)', text)
    return result 

这将 return 给定键的值,您必须对要提取值的所有键执行此操作

Regex demo

您可以使用

query_string(str, key) {
    RegExMatch(str, "O)\b" key "\s*:\s*(\d+)", output)
    return output[1]

正则表达式看起来像 \bA\s*:\s*(\d+) 并且匹配:

  • \b - 单词边界
  • A - 您将传递给方法的密钥
  • \s*:\s* - 用 0+ 个空格括起来的冒号
  • (\d+) - 第 1 组:任何一个或多个数字。

O) 内联选项 tells AHK 将匹配结果输出为 OutputVar 变量,以便您可以从 output[1] 中获取所需的值:

If a capital O is present in the RegEx's options -- such as "O)abc.*123" -- a match object is stored in OutputVar. This object can be used to retrieve the position, length and value of the overall match and of each captured subpattern, if present.