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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.