The Journey of #100DaysofCode (@eliehannouch)

100daysofcode - Day 18

Hello folks, hope you are doing well, and you are learning some amazing things in this amazing tech world. :muscle::star_struck:

In yesterday’s post, we talked about string formatting in Golang. And in today’s post we will define the regular expressions in Golang. How to use them and to do so ? :smiling_face_with_three_hearts::sunglasses::boom:

What is a regular expression ?

  • A regular expression :pushpin: (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for “find” or “find and replace” operations on strings, or for input validation. :fist::blush::innocent:

Application of regular expression ? :desktop_computer:

  • Simple parsing.

  • The production of syntax highlighting systems. :pencil2:

  • Data Validation. :white_check_mark:

  • Data Scraping (especially web scraping)

  • Data wrangling.

Example

    package main
     
    import (
       "fmt"
       "regexp"
    )
     
    func main() {
     
       match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
       fmt.Println(match)
     
       r, _ := regexp.Compile("p([a-z]+)ch")
     
       fmt.Println(r.MatchString("peach"))
     
       fmt.Println(r.FindString("peach punch"))
     
       fmt.Println("idx:", r.FindStringIndex("peach punch"))
     
       fmt.Println(r.FindStringSubmatch("peach punch"))
     
       fmt.Println(r.FindStringSubmatchIndex("peach punch"))
     
       fmt.Println(r.FindAllString("peach punch pinch", -1))
     
       fmt.Println("all:", r.FindAllStringSubmatchIndex(
           "peach punch pinch", -1))
     
       fmt.Println(r.FindAllString("peach punch pinch", 2))
     
       fmt.Println(r.Match([]byte("peach")))
     
       r = regexp.MustCompile("p([a-z]+)ch")
       fmt.Println("regexp:", r)
     
       fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
     
       /*
           true
           true
           peach
           idx: [0 5]
           [peach ea]
           [0 5 1 3]
           [peach punch pinch]
           all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
           [peach punch]
           true
           regexp: p([a-z]+)ch
           a <fruit>
           a PEACH
       */
     
    }

4 Likes