SoFunction
Updated on 2025-03-01

Example of Go regular expressions

package main
import "bytes"
import "fmt"
import "regexp"
func main() {
//This tests whether a string conforms to an expression.
    match, _ := ("p([a-z]+)ch", "peach")
    (match)
//Above we are using strings directly, but for some other regular tasks, you need to use Compile to an optimized Regexp structure.
    r, _ := ("p([a-z]+)ch")
//There are many methods for this structure. Here is a matching test similar to the one we saw earlier.
    (("peach"))
//This is to find the matching string.
    (("peach punch"))
//This is also to find the first matching string, but the matching start and end position index is returned, rather than the matching content.
    (("peach punch"))
//Submatch returns a string that matches exactly and locally. For example, information about p([a-z]+)ch and `([a-z]+) will be returned here.
    (("peach punch"))
// Similarly, this will return the index position of the exact match and the local match.
    (("peach punch"))
//This function with All returns all matches, not just the first match. For example, find all items matching expressions.
    (("peach punch pinch", -1))
//All can also correspond to all the functions above.
    ((
        "peach punch pinch", -1))
//This function provides a positive integer to limit the number of matches.
    (("peach punch pinch", 2))
//In the example above, we used strings as parameters and used methods such as MatchString. We can also provide the []byte parameter and remove the String from the function hit.
    (([]byte("peach")))
//When creating regular representation constants, you can use Compile's variant MustCompile. Because Compile returns two values, it cannot be used as a constant.
    r = ("p([a-z]+)ch")
    (r)
//The regexp package can also be used to replace some strings with other values.
    (("a peach", "<fruit>"))
//Func variable allows matching content to be passed into a given function.
    in := []byte("a peach")
    out := (in, )
    (string(out))
}