thqby / AutoHotkey_H

AutoHotkey - macro-creation and automation-oriented scripting utility for Windows.
https://autohotkey.com/
GNU General Public License v2.0
97 stars 9 forks source link

增加更多的正则方法 #82

Closed DeepTulip closed 9 months ago

DeepTulip commented 9 months ago

相比其他语言丰富的正则 std,AutoHotkey 只提供 RegExMatch/RegExReplace 两个原始方法,一些常见方法都需要自行包装。 在这里,我想讨论下 ahk 内置这些方法的可行性/合理性。

我自用的 lib/rem.ahk 只有两个函数。rem_num() 简单地返回匹配值,不关心其他。rem_list() 返回所有线性匹配。 在 90% 的正则场景我都在使用这两个函数,配合"#UseStdLib",调用起来和内置函数一样简单。 为何我希望它们被内置: 1,性能。底层用 C 实现,性能更好,也跳过了脚本解析生成的过程。 2,更统一。老 AutoHotkey 用户应该都会包装类似的函数 (自认为),那么提供内置函数,避免了分裂和重复。 3,易用性。除非 RegExMatch 能支持更简单的语法糖,否则简单场景 rem_num() 都是更好选择。

rem_num(s, r, t := 0, p := 1) => RegExMatch(s, r, &f, p) ? t < 0 ? f : f[t] : ''

rem_list(s, r, t := 0, p := 1, out := []) {
    f := { pos: p, len: 0 }
    if IsObject(t)
    {
        While RegExMatch(s, r, &f, f.pos + f.len)
        {
            jo := t.clone()
            for i, n in t
                jo.%i% := f[n]
            out.push(jo)
        }
    } else if t < 0
    {
        While RegExMatch(s, r, &f, f.pos + f.len)
            out.push(f)
    } else
    {
        While RegExMatch(s, r, &f, f.pos + f.len)
            out.push(f[t])
    }
    return out.length ? out : ''
}
thqby commented 9 months ago

为简单仅部分差异化的功能增加函数是有点多余的

rem_list可以用RegExReplace第三参数传递回调函数实现

DeepTulip commented 9 months ago

拿 rust 的字符串 trim 方法来说,它提供了很多差异不大的方法: trim trim_end trim_end_matches trim_left trim_left_matches trim_matches trim_right trim_right_matches trim_start trim_start_matches

再加上众多其他截取字符串方法,这些可以说非常"多余"。 但事实是,这真的极大提升了易用性。

如果有三个选项。1,使用内置 rem_list(); 2,在需要时手写线性正则提取;3,写一个函数,在 RegExReplace() 中提取。你认为 3 有优势吗?

thqby commented 9 months ago

脚本语言和编译型语言不一样,后者可以在编译时通过去除未使用函数、内联等优化掉不必要的函数,可以尽可能多的提供各种各样的函数,而ahk不能,在小巧和易用性上需要有所取舍

RegExReplace(str,re, ObjBindMethoed(out:=[],'push')) 上面是rem_list的一种实现

rem_num或许可以增加o)正则选项,返回对象

DeepTulip commented 9 months ago

ok,我本来觉得,这是 可实现 (比如 dllcall可以实现所有注册表功能)/ 最优解 (内置注册表命令) 之间,一个不平衡的地方,看来并不是。

rem_num 参数3 输入 -1 是返回对象。