regular expression

sehyoung·2022년 4월 26일
0

Golang

목록 보기
4/5
post-thumbnail

Overview

what is regular expression?

A regular expression(regex or regexp) is a notation for describing sets of character strings.

use cases

  • "find" or "replace" operations on strings
  • Input validation

golang library

regexp

  • standard library
  • It's the syntax accepted by RE2.

syntax

MetacharacterDescription
.any character, possibly including newline
[xyz]character class
[^xyz]negated character class
\1backreference (NOT SUPPORTED)
A-Zcharacter range
x+one or more x

e.g.
a.c -> "abc"
[a.c] -> "a", "." or "c"
[abc] -> "a", "b" or "c"
[^ab] -> matches any character other than "a" or "b"
[a-z0-9] -> matches from "a" to "z" and from "0" to "9"

Note that

👉 RE2 doesn't support '\'(backreferences) in order to guarantee linear-time execution.

👉 To match a metacharacter, escape it with a backslash: '\'+ matches a literal plus character. (In order to remove their special meaing, prefix those characters with '\')

👉 The difference between Double Quote(") and Backtick(`) in Golang.
double quote(") - backslash('\') is recognized as escape character.
back quote(') => backslash('\') has not special meaning.

practice

import "regexp"

// regexp.MatchString(`(.)\1\1+`, pw) <- not support
pw := "abcd1234"
match, err := regexp.MatchString(`[^A-Za-z0-9]`, pw)


tag := "varchar(20);unique"
reg := regexp.MustCompile(`varchar\([0-9]+\)`)
r := reg.FindStringSubmatch(tag)
// r[0] varchar(20)

refrence

https://pkg.go.dev/regexp
https://github.com/google/re2/wiki/Syntax

profile
Keep turnin' the pages

0개의 댓글