Split. Suppose a Go string has several important values in it, placed between delimiter characters or sequences. We can access just those values with a Split regexp call.
With Split, it often helps to think in terms of "not" metacharacters—so we specify a delimiter, for example, of "not" word characters. Split tries to match delimiters.
Example. 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.
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])
}
}carrot
cat
dog
Numbers. Occasionally we may want to extract the numbers from a string. We can use Split along with the strconv.Atoi method to accomplish this task.
Here We split on one or more non-digit characters, which leaves us with the digit sequences of the string.
Then In the for-loop, we must ensure we have at least 1 digit character by testing len, and then call Atoi on each substring.
package main
import (
"fmt""regexp""strconv"
)
func main() {
value := "10 20 30, 50?"// Get all numbers by separating on non-numeric characters.
result := regexp.MustCompile(`\D+`).Split(value, -1)
// Display all numbers in the string.
for _, s := range(result) {
if len(s) >= 1 {
number, _ := strconv.Atoi(s)
fmt.Println(number, ",", number + 1)
}
}
}10 , 11
20 , 21
30 , 31
50 , 51
Summary. The regexp package in Go provides a more powerful version of the Split string method. This regexp.Split method allows each delimiter to matched with a pattern.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.