V
V
Vladimir Grabko2016-06-06 18:46:12
go
Vladimir Grabko, 2016-06-06 18:46:12

How to use regex?

I read on the Internet that Go has such a cool thing as compiling regular expressions. (I found MustCompile in the docks) but I did not understand how to use it. Let's say I have js

var loginRex = /^[.\-\a-zA-Z0-9]+$/i;
if(!loginRex.test(login)){
//обработаем ошибку валидации
}

How to write the same thing but only in Go?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
fastpars, 2016-06-06
@VGrabko

https://golang.org/pkg/regexp/
There is an Example at the end of Overview:

package main

import (
  "fmt"
  "regexp"
)

func main() {
  // Compile the expression once, usually at init time.
  // Use raw strings to avoid having to quote the backslashes.
  var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)

  fmt.Println(validID.MatchString("adam[23]"))
  fmt.Println(validID.MatchString("eve[7]"))
  fmt.Println(validID.MatchString("Job[48]"))
  fmt.Println(validID.MatchString("snakey"))
}

PS you don't need ignore case. [a-zA-Z]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question