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
來源:掘金
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章