nginx 正则表达式 简单方便快速 验证方法

之前在配置时都是本地起一个nginx服务,修改location规则,然后nginx -s reload 或则 service nginx reload不断尝试来判断是否符合预期。显而易见,效率极低。使用一些在线正则表达式测试(e.g. 在线工具)又因为使用的库不同,多少存在差异。

正则表达式有不同的规则引擎,具体参见 wikipedia的 Comparison of regular expression engines

nginx使用的是PCRE

截取nginx官方文档 Building nginx from Sources

--with-pcre=path — sets the path to the sources of the PCRE library. The library distribution (version 4.4 — 8.40) needs to be downloaded from the PCRE site and extracted. The rest is done by nginx’s ./configure and make. The library is required for regular expressions support in the location directive and for the ngx_http_rewrite_module module.

建议使用linux下的 grep 工具

windows可以使用cygwin 或者git for windows中的git-bash.exe

$ grep --help

# ...

Regexp selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
  -F, --fixed-strings       PATTERN is a set of newline-separated strings
  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  -e, --regexp=PATTERN      use PATTERN for matching
  -f, --file=FILE           obtain PATTERN from FILE
  -i, --ignore-case         ignore case distinctions
  -w, --word-regexp         force PATTERN to match only whole words
  -x, --line-regexp         force PATTERN to match only whole lines
  -z, --null-data           a data line ends in 0 byte, not newline

# ...复制代码

使用 grep -P命令即可

$ echo 'a.gif' | grep -P '\.(jp?g|gif|bmp|png)'

#输出
a.gif复制代码

如果只想输出匹配部分,则加上-o参数

$ echo 'a.gif' | grep -P -o '\.(jp?g|gif|bmp|png)'

#输出
.gif复制代码

具体 perl 正则表达式语法,可参考

Perl regular expressions man page

汤姆的猫-Perl入门(四)Perl的正则表达式

 

作者:赵安家

链接:https://juejin.im/post/6844903485721296910
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章