之前在配置时都是本地起一个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
博客 anjia.ml/2017/06/29/…
简书 www.jianshu.com/p/17eb0ba22…
掘金 juejin.im/post/5954ad…