Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of regular expressions in Go language

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the Go language regular expression case analysis related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this Go language regular expression case analysis article will have something to gain, let's take a look.

Preface

In calculation, we often need to match a character or a subset of characters of a particular pattern to a string in another string. This technique is used to use special syntax to search for a specific character set in a given string.

If the searched pattern matches, or if a given subset is found in the target string, the search is called successful; otherwise, it is considered unsuccessful.

What is a regular expression

A regular expression (or RegEx) is a special sequence of characters that defines a search pattern for matching specific text. In Golang, there is a built-in regular expression package: the regexp package, which contains a list of all actions, such as filtering, modifying, replacing, validating, or extracting.

Regular expressions can be used for text searches and more advanced text operations. Regular expressions are built into tools such as grep and sed, text editors such as vi and emacs, and programming languages such as Go, Java and Python. The syntax of expressions mainly follows the established RE2 syntax used in these popular languages. The RE2 syntax is a subset of PCRE and has a variety of considerations.

MatchString function

The MatchString () function reports whether the string passed as an argument contains any matches of the regular expression pattern.

Package mainimport ("fmt"log"regexp") func main () {words: = [...] string {"Seven", "even", "Maven", "Amen", "eleven"} for _, word: = range words {found, err: = regexp.MatchString (".even", word) if err! = nil {log.Fatal (err)} if found {fmt.Printf ("% s matches\ n", word)} else {fmt.Printf ("% s does not match\ n", word)}

Run the code:

Seven matches

Even does not match

Maven does not match

Amen does not match

Eleven matches

But at the same time, we can see a hint from the editor:

The compiler has begun to remind us that the performance of MatchString direct use is very poor, so consider using the regexp.Compile function.

Compile function

The Compile function parses the regular expression and, if successful, returns a Regexp object that can be used to match the text. Compiled regular expressions produce faster code.

The MustCompile function is a convenience function that compiles regular expressions and panic occurs when the expression cannot be parsed.

Package mainimport ("fmt"log"regexp") func main () {words: = [...] string {"Seven", "even", "Maven", "Amen", "eleven"} re, err: = regexp.Compile (".even") if err! = nil {log.Fatal (err)} for _, word: = range words {found: = re.MatchString (word) if found {fmt.Printf ("% s matches\ n", word)} else {fmt.Printf ("% s does not match\ n") Word)}

In the code example, we used a compiled regular expression.

Re, err: = regexp.Compile (".even")

Even if you compile regular expressions with Compile. Then call the MatchString function on the returned regular expression object:

Found: = re.MatchString (word)

Run the program, and you can see the same code:

Seven matches

Even does not match

Maven does not match

Amen does not match

Eleven matches

MustCompile function package mainimport ("fmt"regexp") func main () {words: = [...] string {"Seven", "even", "Maven", "Amen", "eleven"} re: = regexp.MustCompile (".even") for _, word: = range words {found: = re.MatchString (word) if found {fmt.Printf ("% s matches\ n", word)} else {fmt.Printf ("% s does not match\ n", word)}} FindAllString function

The FindAllString function returns all consecutive matching slices of the regular expression.

Package mainimport ("fmt"os"regexp") func main () {var content = `Foxes are omnivorous mammals belonging to several generaof the family Canidae. Foxes have a flattened skull, upright triangular ears,a pointed, slightly upturned snout, and a long bushy tail. Foxes live on everycontinent except Antarctica. By far the most common and widespread species offox is the red Fox.`re: = regexp.MustCompile ("(? I) fox (es)?") found: = re.FindAllString (content,-1) fmt.Printf ("% Q\ n", found) if found = = nil {fmt.Printf ("no match found\ n") os.Exit (1)} for _, word: = range found {fmt.Printf ("% s\ n", word)}}

In the code example, we found all the occurrences of the word fox, including its plural.

Re: = regexp.MustCompile ("(?) fox (es)?")

Using the (? I) syntax, regular expressions are not case-sensitive. (es)? The "es" character may contain zero or once.

Found: = re.FindAllString (content,-1)

We use FindAllString to find all the defined regular expressions that appear. The second parameter is the largest match to find;-1 searches for all possible matches.

Running result:

["Foxes"fox"fox"]

Foxes

Foxes

Foxes

Fox

Fox

FindAllStringIndex function package mainimport ("fmt"regexp") func main () {var content = `Foxes are omnivorous mammals belonging to several generaof the family Canidae. Foxes have a flattened skull, upright triangular ears,a pointed, slightly upturned snout, and a long bushy tail. Foxes live on everycontinent except Antarctica. By far the most common and widespread species offox is the red Fox.`re: = regexp.MustCompile ("(? I) fox (es)?") idx: = re.FindAllStringIndex (content,-1) for _, j: = range idx {match: = content [j [0]: J [1]] fmt.Printf ("% s at% d\ n", match, j [0], j [1])}}

In the code example, we find all the fox words and their indexes that appear in the text.

Foxes at 0:5

Foxes at 81:86

Foxes at 196:201

Fox at 296:299

Fox at 311:314

Split function

The Split function cuts a string into substrings separated by a defined regular expression. It returns substring slices between these expression matches.

Package mainimport ("fmt"log"regexp"strconv") func main () {var data = `22,1,3,4,5,17,4,3,21,4,5,1,48,9,42`sum: = 0re: = regexp.MustCompile (",\ s *") vals: = re.Split (data,-1) for _, val: = range vals {n, err: = strconv.Atoi (val) sum + = nif err! = nil {log.Fatal (err)} fmt.Println (sum)}

In the code example, we have a comma-separated list of values. We truncate the values from the string and calculate their sum.

Re: = regexp.MustCompile (",\ s*")

A regular expression includes a comma character and any number of adjacent spaces.

Vals: = re.Split (data,-1)

We got a portion of the value.

For _, val: = range vals {n, err: = strconv.Atoi (val) sum + = nif err! = nil {log.Fatal (err)}}

We traverse the slices and calculate the sum. Slices contain strings; therefore, we use the strconv.Atoi function to convert each string to an integer.

Run the code:

one hundred and eighty nine

Go regular expression capture group

Parentheses () are used to create a capture group. This allows us to apply quantifiers to the entire group or to restrict alternation to part of the regular expression. To find the capture group (Go uses the jargon subexpression), we use the FindStringSubmatch function.

Package mainimport ("fmt"regexp") func main () {websites: = [...] string {"webcode.me", "zetcode.com", "freebsd.org", "netbsd.org"} re: = regexp.MustCompile ("(\ w +)\. (\ w +)") for _, website: = range websites {parts: = re.FindStringSubmatch (website) for I _: = range parts {fmt.Println (parts [I])} fmt.Println ("-")}}

In the code example, we use groups to divide the domain name into two parts.

Re: = regexp.MustCompile ("(\ w +)\. (\ w +)")

We define two groups in parentheses.

Parts: = re.FindStringSubmatch (website)

FindStringSubmatch returns a string slice containing a match, including a string from the capture group.

Run the code:

$go run capturegroups.go

Webcode.me

Webcode

Me

-

Zetcode.com

Zetcode

Com

-

Freebsd.org

Freebsd

Org

-

Netbsd.org

Netbsd

Org

-

Regular expression replacement string

You can replace strings with ReplaceAllString. This method returns the modified string.

Package mainimport ("fmt"io/ioutil"log"net/http"regexp"strings") func main () {resp, err: = http.Get ("http://webcode.me")if err! = nil {log.Fatal (err)} defer resp.Body.Close () body, err: = ioutil.ReadAll (resp.Body) if err! = nil {log.Fatal (err)} content: = string (body) re: = regexp.MustCompile ("] * > ") replaced: = re.ReplaceAllString (content) "") fmt.Println (strings.TrimSpace (replaced))}

The example reads the HTML data of a Web page and uses a regular expression to remove its HTML tags.

Resp, err: = http.Get ("http://webcode.me")

We use the Get function in the http package to create an GET request.

Body, err: = ioutil.ReadAll (resp.Body)

We read the body of the response object.

Re: = regexp.MustCompile ("] * >")

This pattern defines a regular expression that matches the HTML tag.

Replaced: = re.ReplaceAllString (content, "")

We use the ReplaceAllString method to delete all tags.

ReplaceAllStringFunc function

ReplaceAllStringFunc returns a copy of a string in which all matches of the regular expression have been replaced with the return value of the specified function.

Package mainimport ("fmt"regexp"strings") func main () {content: = "an old eagle" re: = regexp.MustCompile (`[^ aeiou]`) fmt.Println (re.ReplaceAllStringFunc (content, strings.ToUpper))}

In the code example, we apply the strings.ToUpper function to all characters of the string.

This is the end of $go run replaceallfunc.goaN oLD eaGLe's article on "example Analysis of regular expressions in Go language". Thank you for reading! I believe you all have a certain understanding of the knowledge of "Go regular expression case analysis". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report