4

rex:Golang的正则表达式生成器

 1 year ago
source link: https://www.jdon.com/61156
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

rex:Golang的正则表达式生成器
它提高了可读性,并有助于使用人性化的结构构建正则表达式。此外,它允许注释和重用块,从而提高代码质量。
它只是一个构建器,所以它返回标准*regexp.Regexp。用字符串切换到普通的正则表达式没有问题。:)
该库支持大多数正则表达式语法。

示例 ipv4 检查:

ipv4Octet := rex.Group.Composite(
    // One of 250-255 | 200-249 | 0-199.
    rex.Group.Define( // 250-255.
        rex.Common.Text("25"),
        rex.Chars.Range('0', '5'),
    ).NonCaptured(),
    rex.Group.Define( // 200-249.
        rex.Chars.Single('2'),
        rex.Chars.Range('0', '4'),
        rex.Chars.Digits(),
    ).NonCaptured(),
    rex.Group.Define( // 000-199.
        rex.Chars.Runes("01").Repeat().ZeroOrOne(),
        rex.Chars.Digits(),
        rex.Chars.Digits().Repeat().ZeroOrOne(),
    ).NonCaptured(),
).NonCaptured()

rex.New(rex.Group.Define(
    rex.Group.Define(
        ipv4Octet,
        // Numbers are divided by a dot.
        rex.Chars.Single('.'),
    ).NonCaptured().Repeat().Exactly(3),
    ipv4Octet,
)).String() // Or MustCompile or Compile.

它将产生以下正则表达式:

^(?:(?:(?:(?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d\d?))\.){3}(?:(?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d\d?)))$

它需要更多的代码,但它有助于简单地使用可重用的块和模式来描述正则表达式。

它有常见的可重用块,如rex.Helper.Phone(),rex.Helper.IP()等。
更多示例:

https://github.com/hedhyw/rex/blob/main/examples_test.go


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK