TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Regexp Examples: MatchString, MustCompile

Use the regexp package for regular expressions. Call MatchString and compile patterns.
Regexp. In Go, we find an optimized regular expression engine. This runs in linear time, making complex patterns faster. It is located in the regexp package.
With MatchString, we see if a pattern can match a string. This tells us if the string satisfies the pattern's requirements. We use Compile to create reusable objects.
MatchString example. This program uses the MatchString method without first creating a Regexp instance. This means that a compiled expression is not reused.

Pattern: We use some metacharacters in the pattern. The period means "any character" and the plus means "one or more."

Result: The first return value (matched) is a boolean that is true if the pattern matched. The second is an error value (which may be nil).

Golang program that uses regexp.MatchString package main import ( "fmt" "regexp" ) func main() { value := "cat" // See if this regular expression matches. matched, _ := regexp.MatchString(".+t", value) // Test the result. if matched { fmt.Println(true) } } Output true
Compile regexp. A regexp can be compiled. Once compiled, it can be reused many times with no delays before calls. Many methods, like MatchString are available on regexp instances.

MustCompile: This method compiles a regular expression and returns the instance. It will cause an error (panic) if the pattern is invalid.

Here: We loop over the strings in a slice and attempt to match each string with the compiled regular expression.

Slice
Golang program that compiles regexp and uses MatchString package main import ( "fmt" "regexp" ) func main() { // Compile this regular expression. var lettersDigits = regexp.MustCompile(`\w\w\w\d\d\d`) // Some strings to test. values := []string{"cat100", "dog200", "bird", "200fish"} // Loop over our strings and call MatchString on them. for i := range values { result := lettersDigits.MatchString(values[i]) fmt.Printf("%v = %v\n", values[i], result) } } Output cat100 = true dog200 = true bird = false 200fish = false
Split. This method is called on a regexp instance. We first compile the delimiter pattern (specified as a regular expression). Each substring is separated based on matches of this pattern.

Argument 1: This is the string we want to split. This should have delimiters (like commas or spaces).

Argument 2: The second argument to Split() is the maximum number of substrings to get. We use a negative number to indicate no limit.

Golang program that uses Split, regexp package main import ( "fmt" "regexp" ) func main() { value := "carrot,cat;dog" // Compile the delimiter as a regular expression. re := regexp.MustCompile(`\W`) // Call split based on the delimiter pattern. // ... Get all substrings. result := re.Split(value, -1) // Display our results. for i := range(result) { fmt.Println(result[i]) } } Output carrot cat dog
Find, FindAllString. With Find() and other methods like FindAllString(), a search is performed before matching occurs. So the entire string does not need to match—only parts do.Find
A summary. The regexp package is a prized feature in Go. Unlike older languages like Perl, Go uses more advanced logic to compile and execute these text programs.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf