nginx正則表達式快捷測試方法

以前在配置時都是本地起一個nginx服務,修改location規則,而後nginx -s reload 或則 service nginx reload不斷嘗試來判斷是否符合預期。顯而易見,效率極低。使用一些在線正則表達式測試(e.g. 在線工具)又由於使用的庫不一樣,多少存在差別。html

正則表達式有不一樣的規則引擎,具體參見 wikipedia的 Comparison of regular expression engineslinux

nginx使用的是PCREnginx

截取nginx官方文檔 Building nginx from Sourcesgit

--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.github

建議使用linux下的 grep 工具正則表達式

windows能夠使用cygwin 或者git for windows中的git-bash.exeexpress

$ 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命令便可windows

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

#輸出
a.gif複製代碼

若是隻想輸出匹配部分,則加上-o參數bash

$ 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…

相關文章
相關標籤/搜索