正则表达式不匹配方案中的字符串但适用于其他平台

Regex not matching string in scheme but works on other platform

我正在 运行宁 string-match 使用模式 [ \[\]a-zA-Z0-9_:.,/-]+ 来匹配示例文本 Text [a,b]。虽然该模式适用于 regex101,但当我 运行 它在 scheme it returns #f 上时。这是 regex101 link.

这是我运行宁

的功能

(string-match "[ \[\]a-zA-Z0-9_:.,/-]+" "Text [a,b]")

为什么它不能在 scheme 上工作但在其他地方工作?我错过了什么吗?

我没有发现您的正则表达式语法有任何问题,因为它被正确引用了,所以我认为 Guile 或它使用的正则表达式库中一定存在错误,而 \] 只是没有解释括号内的正确方法。我通过使用八进制代码点值找到了解决方法:

(string-match "[A-Za-z\[\0135]+" "Text [a,b]")
; ==> #("Text [a,b]" (0 . 4))

你的正则表达式不是很好。它匹配这些字符的任意组合,因此 "]/Te,3.xt[2" 也匹配。如果您期望像 "Something [something, something]" 这样的字符串,我宁愿使用 /[A-Z][a-z0-9]+ [[a-z0-9]+,[a-z0-9]+]/ 来代替。例如。

(define pattern "[A-Z][a-z0-9]+ \[[a-z0-9]+,[a-z0-9]+\]") 
(string-match pattern "Test [q,w]")     ; ==> #("Test [q,w]" (0 . 10))
(string-match pattern "Be100 [sub,45]") ; ==> #("Be100 [sub,45]" (0 . 14))

在 guile gnu 邮件列表上讨论了这个问题后,我发现 Guile 的 (ice-9 regex) 库使用了 POSIX 扩展正则表达式。而且这种正则表达式不支持字符转义 类 [..],因此这就是它不匹配字符串的原因。

但是,我使用以下函数作为变通方法并且有效:

(string-match "[][a-zA-Z]+" "Text[ab]")