Go 正則表達式庫之 commonregex

爲什麼使用 commonregex?

在開發的時候,我們會遇到一些需要使用字符串的匹配和查找的任務。我們可以使用正則表達式去提取感興趣的數據,如手機號碼,郵件,超鏈接等。但是正則表達式寫起來費時費力,而且容易遺忘。commonregex 它提供了很多內置的正則表達式,開箱即用,能極大的提高開發體驗和開發效率。

commonregex 簡介

提供經常使用的正則表達式的集合。

它提供了這些作爲獲取與特定模式對應的匹配字符串的簡單函數。

快速使用 commonregex

安裝 commonregex

go get -u github.com/mingrammer/commonregex

簡單使用 commonregex

package main

import (
  "fmt"

  cregex "github.com/mingrammer/commonregex"
)

func main() {
  text := `John, please get that article on www.linkedin.com to me by 5:00PM on Jan 9th 2012. 4:00 would be ideal, actually. If you have any questions, You can reach me at (519)-236-2723x341 or get in touch with my associate at harold.smith@gmail.com`

  dateList := cregex.Date(text)
  timeList := cregex.Time(text)
  linkList := cregex.Links(text)
  phoneList := cregex.PhonesWithExts(text)
  emailList := cregex.Emails(text)

  fmt.Println("date list:", dateList)
  fmt.Println("time list:", timeList)
  fmt.Println("link list:", linkList)
  fmt.Println("phone list:", phoneList)
  fmt.Println("email list:", emailList)
}

運行結果:

date list: [Jan 9th 2012]
time list: [5:00PM 4:00 ]
link list: [www.linkedin.com harold.smith@gmail.com]
phone list: [(519)-236-2723x341]
email list: [harold.smith@gmail.com]

commonregex提供的 API 非常易於使用,調用相應的類別方法返回一段文本中符合這些格式的字符串列表。

上面依次從text獲取日期列表時間列表超鏈接列表電話號碼列表電子郵件列表

總結

commonregex 提供了常用的正則表達式的函數,足以應付我們日常開發場景,能較大的提高我們的開發效率。

參考資料

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://gocn.vip/topics/12143