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 Find Examples: FindAllString

Use the Find and FindAllString funcs on regexp. Loop over the results.
Find. With regexp we are often trying to find strings within a larger string. We use patterns (passed to MustCompile) to determine which values match.
To use Find, we must have byte slices. This is inconvenient in some programs. We can use a method like FindAllString instead, to operate directly on strings.
Find example. Here we use Find. We try to find a 3-digit sequence that begins with the value 2. The Find method returns the leftmost matching sequence as a byte slice.

Important: With byte slices, we must convert them back to strings before printing them. This can be annoying.

Golang program that uses Find package main import ( "fmt" "regexp" ) func main() { // Match 3-digit values starting with 2. re := regexp.MustCompile("2\\d\\d") // Use find to get leftmost match. result := re.Find([]byte("123 124 125 205 211")) // Convert back to string and print it. fmt.Println(string(result)) } Output 205
FindAllString. This func finds multiple matches of a pattern within a string. It returns the values in a slice—we can loop over it with a for-loop.For

String: We operate directly on strings with FindAllString the results are in a slice of strings, so we can print them with no conversion.

Golang program that uses FindAllString package main import ( "fmt" "regexp" ) func main() { // Match 3-char values starting with digit 1. re := regexp.MustCompile("1..") // Find and loop over all matching strings. results := re.FindAllString("123 124 125 200 211", -1) for i := range(results) { fmt.Println(results[i]) } } Output 123 124 125
A review. With Find-methods, we perform a search within the source string—the entire string is not matched as in MatchString(). We can test matches in a for-loop after the method call.Regexp
© 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