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.
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.
string
we want to split. This should have delimiters (like commas or spaces).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
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.
string
.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
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.