I'd like to point all of my visitors to "single subdirectories" to one page, and all visitors to "double subdirectories" to another. E.g:
我想将所有访问者的“单个子目录”指向一个页面,将所有访问者指向“双子目录”到另一个页面。例如:
/foo/
/new/
/north/
/1-j4/
Would all point to 1.app, whereas
都会指向1.app,而
/foo/bar/
/new/york/
/north/west/
/1-j4/a_990/
Would all point to 2.app.
都指向2.app。
I figured I could do this with non-greedy regex matching, like so:
我想我可以用非贪婪的正则表达式匹配来做到这一点,如下所示:
- url: /(.*?)/$
script: 1.app
- url: /(.*?)/(.*?)/$
script: 2.app
To my confusion, both /foo/ and /foo/bar/ resolve to script 1.app. Does the "lazy" regex force itself up to include the middle /, since that's the only way to get a match? How else can I do this? I have tried using (\w*?) but get the same result.
令我困惑的是,/ foo /和/ foo / bar /解析为脚本1.app。 “懒惰”的正则表达式是否强制包含中间/,因为这是获得匹配的唯一方法?我怎么能这样做?我尝试过使用(\ w *?)但得到了相同的结果。
2 个解决方案
#1
1
The .*?
will still match through any amount of /
because .
matches any character but a line break char (by default). You need to base your regexps on a negated character class, [^/]*
, that matches 0 or more chars other than /
.
。*?仍会匹配任何数量的/因为。匹配任何字符,但匹配换行符(默认情况下)。你需要将你的正则表达式建立在一个否定的字符类[^ /] *上,它与0之外的0或更多字符匹配。
To match directories with one part, use ^([^/]*)/?$
and to match those with 2, use ^([^/]*)/([^/]*)/?$
.
要将目录与一个部分匹配,请使用^([^ /] *)/?$并与2匹配,使用^([^ /] *)/([^ /] *)/?$。
Note that if you plan to use the patterns in online Web testers, you will have to escape /
in most of them as by default they use /
symbol as a regex delimiter.
请注意,如果您计划在联机Web测试程序中使用这些模式,则必须在大多数情况下使用它们,因为默认情况下它们使用/符号作为正则表达式分隔符。
#2
1
Yes, the (.*?)
includes slashes, so will resolve to 1.app
. If you put the 2.app
handler first, it should do what you want:
是的,(。*?)包含斜杠,因此将解析为1.app。如果你首先放置2.app处理程序,它应该做你想要的:
- url: /(.*?)/(.*?)/$
script: 2.app
- url: /(.*?)/$
script: 1.app
#1
1
The .*?
will still match through any amount of /
because .
matches any character but a line break char (by default). You need to base your regexps on a negated character class, [^/]*
, that matches 0 or more chars other than /
.
。*?仍会匹配任何数量的/因为。匹配任何字符,但匹配换行符(默认情况下)。你需要将你的正则表达式建立在一个否定的字符类[^ /] *上,它与0之外的0或更多字符匹配。
To match directories with one part, use ^([^/]*)/?$
and to match those with 2, use ^([^/]*)/([^/]*)/?$
.
要将目录与一个部分匹配,请使用^([^ /] *)/?$并与2匹配,使用^([^ /] *)/([^ /] *)/?$。
Note that if you plan to use the patterns in online Web testers, you will have to escape /
in most of them as by default they use /
symbol as a regex delimiter.
请注意,如果您计划在联机Web测试程序中使用这些模式,则必须在大多数情况下使用它们,因为默认情况下它们使用/符号作为正则表达式分隔符。
#2
1
Yes, the (.*?)
includes slashes, so will resolve to 1.app
. If you put the 2.app
handler first, it should do what you want:
是的,(。*?)包含斜杠,因此将解析为1.app。如果你首先放置2.app处理程序,它应该做你想要的:
- url: /(.*?)/(.*?)/$
script: 2.app
- url: /(.*?)/$
script: 1.app