100daysofcode - Day 18
Hello folks, hope you are doing well, and you are learning some amazing things in this amazing tech world. ![]()
![]()
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 ? ![]()
![]()
![]()
What is a regular expression ?
- A regular expression
(shortened as regexorregexp; 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.


Application of regular expression ?
-
Simple parsing.
-
The production of syntax highlighting systems.

-
Data Validation.

-
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
*/
}