英文:
My (valid?) regex doesn't work in gorilla/mux
问题
我在我的代码中有这个正则表达式:
get.HandleFunc("/my/api/user/{userID:^([1-9][0-9]*)$}", app.Handle("user"))
但是当我运行测试时,只返回404错误。我还尝试了这个:
get.HandleFunc("/my/api/user/{userID:\\A([1-9][0-9]*)\\z}", app.Handle("user"))
它在我的旧的(但不正确的)正则表达式上完美运行:
get.HandleFunc("/my/api/user/{userID:[0-9]{1,}}", app.Handle("user"))
我想知道我的新正则表达式有什么问题。我尝试在一些网站上测试它,还使用Go的regexp
包进行测试,它总是有效的。据我所知,gorilla/mux
使用Go的regexp
包。有什么想法吗?
我想要的是检测正整数(不包括零)。
英文:
I have this regex in my code:
get.HandleFunc("/my/api/user/{userID:^([1-9][0-9]*)$}", app.Handle("user"))
But when I run the tests, only 404s are returned. I also tried this:
get.HandleFunc("/my/api/user/{userID:\\A([1-9][0-9]*)\\z}", app.Handle("user"))
It worked perfectly with my older (but incorrect) regex:
get.HandleFunc("/my/api/user/{userID:[0-9]{1,}}", app.Handle("user"))
I wonder what is wrong with my new regex. I tried to test it on some websites and also by using the regexp
package in Go, and it always worked. As far as I know, gorilla/mux
uses Go's regexp
package. Any idea?
What I want is to detect positive integers excluding zero.
答案1
得分: 3
锚点很可能是问题所在,你试图在字符串的开头/结尾位置进行断言。
我建议你尝试修改旧的(有效的)正则表达式,如下所示:
get.HandleFunc("/my/api/user/{userID:[1-9][0-9]*}", app.Handle("user"))
英文:
The anchors are most likely the issue here, you're trying to assert at start/end of string positions.
I would simply try modifying the older (working) regular expression as follows:
get.HandleFunc("/my/api/user/{userID:[1-9][0-9]*}", app.Handle("user"))
答案2
得分: 1
如果你想检测正整数(不包括0),你应该使用这个字符类:[1-9]\d*
。
这意味着,第一个数字必须在1和9之间。其他数字(如果存在,参考*
)可以是任意整数,包括0。
英文:
If you want to detect positive integers excluding 0, you should use this characters class: [1-9]\d*
That means, the first digit must be between 1 and 9. The other digits (if present, look at the *
) can be any integer, 0 included.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论