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的正则表达式

博客 anjia.ml/2017/06/29/…
简书 www.jianshu.com/p/17eb0ba22…
掘金 juejin.im/post/5954ad…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值