home.


Tagged: golang-regex


Golang regex basics: Match and find

You can create a regular expressions conforming to RE2 using the Compile or MustCompile method on regexp.

    rp := regexp.MustCompile("[a-z]+")
    rp1, err := regexp.Compile("[a-z]+")

The first panics if the regex is incorrect. The second returns an error message if the regex is incorrect.

You can match with MatchString(str). If you omit the String in the method name, it will expect a byte array.

    foundBool := rp.MatchString("abc")

The Find methods – and others – confirm to this general pattern.

  • The FindString methods returns the first match
  • If you have the word All (FindAllString) in the name it returns a specifed number of matches, or all with -1.

    rp.FindString("abc def") // "abc"
    rp.FindAllString("abc def", -1) // ["abc", "def"]
    
  • If you have the word Submatch (FindAllSubmatch) it will give you any groups in the match, as two dimensional slice.

    rp := regexp.MustCompile("([a-z])([a-z])[a-z]+")
    rp.FindAllStringSubmatch("abc") // ["abc", "a", "b"]
    
  • If you have the word Index at the end it will return a int slice with the starting and ending point of the match, including groups

    rp := regexp.MustCompile("([a-z])([a-z])[a-z]+")
    rp.FindAllStringSubmatchIndex("abc") // [0, 3, 0, 1, 1, 2]
    

The first two ints are the start and end of the match. The next two are the next group match. The next two likewise.

golang golang-regex

Golang regex: Replace and split

You can use the ReplaceAllString methods to replace a string, and manipulate groups if needed.

    rp := regexp.MustCompile("([a-z]+) ([a-z]+)")
    rp.ReplaceAllString("abc def ghi", "$2 $1") // "def abc ghi"

$1 relates to the first group match, and $2 the same. You could just enter text to replace the entireity of the “abc def” string.

ReplaceAllLiteralString allows you to interpret the dollar sign literally.

You can also use a function to do the replacement. You cannot use a groups here, however, as of 1.1.1 anyway.

    rp.ReplaceAllStringFunc("abc def", func(s string) string {
            if(s=="abc") {
                    return "HA"
            } 
            return s        
    }) // "HA def"

You can split a string using the Split method. The second integer argument is the number of splits to perform. -1 means as many as possible.

    rp = regexp.MustCompile("a")
    i := rp2.Split("zzzzazzzzz", -1) // ["zzzz", "zzzz"]
golang golang-regex

Page 1 of 1