【问题标题】:nginx location regex - character class and range of matchesnginx 位置正则表达式 - 字符类和匹配范围
【发布时间】:2013-04-17 00:58:19
【问题描述】:

我正在尝试为路径 /s/<4-6 character string here> 设置一个正则表达式,在该路径中我将 4-6 个字符串捕获为 $1。

我尝试使用以下两个条目,但都失败了

location ~ ^/s/([0-9a-zA-Z]){4,6}+$ { ...

location ~ ^/s/([0-9a-zA-Z]{4,6})+$ { ...

第一个出现“未知指令”,第二个出现“pcre_compile() failed: missing)”

编辑

此位置将提供以下路线:

/s/1234 (and I would capture '1234' in $1)
/s/12345 (and I would capture '12345' in $1)
/s/123456 (and I would capture '123456' in $1)
/s/abcd (and I would capture 'abcd' in $1)
/s/abcde (and I would capture 'abcde' in $1)
/s/abcdef (and I would capture 'abcdef' in $1)
/s/a1b2c (and I would capture 'a1b2c' in $1)

此位置不提供以下路线:

/s/1
/s/12
/s/123
/s/a
/s/ab
/s/abc
/s/abc1234
/s/12345678

等等……

【问题讨论】:

    标签: regex nginx pcre


    【解决方案1】:

    如果要捕获 4 到 6 个字符,为什么不将量词放在捕获括号内?

    可能是这样的:

    location ~ "^/s/([0-9a-zA-Z]{4,6})$" {...
    

    花括号在正则表达式和块控制中都使用,您必须用引号(单引号或双引号)将您的正则表达式括起来(

    【讨论】:

    • 我想捕获并将字符串限制为 4-6 个字符。在前 4 到 6 个字符之后,您有无限个字符,带有 '.*'
    • @Dave:您的要求不明确。请给出您要处理的网址的具体示例。
    • 我认为我的要求很明确。我想从 '/s/1234' 中捕获 '1234' 或从 '/s/abcde' 中捕获 'abcde' 并且除了 4、5 或 6 个字符串之外,不允许在 '/s/' 之后出现任何内容。所以 '/s/x' 或 '/s/xy' 或 '/s/xyz' 或 '/s/abcdxyz' 都不会被这个位置块服务。
    • 'unknown directive "4,6}$' 返回 ^/s/([0-9a-zA-Z]){4,6}$ 和 'pcre_compile() 失败:缺少)在 "^/s/([0-9a-zA-Z]' 中为 ^/s/([0-9a-zA-Z]{4,6})$
    • 好的!这是花括号的原因。您必须将您的正则表达式括在引号之间“
    猜你喜欢
    • 2017-01-03
    • 2014-11-11
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多